我正在处理一些字符串,并使用replace()
从中删除一些字符,例如:
a = 'monsterr'
new_a = a.replace("rr", "r")
new_a
但是,假设现在我收到以下字符串:
在:
a = 'difference'
new_a = a.replace("rr", "r")
new_a
输出:
'difference'
如果我的字符串不包含rr
,我怎么能什么都不返回呢?到底有没有什么过关不还的?我试着:
def check(a_str):
if 'rr' in a_str:
a_str = a_str.replace("rr", "r")
return a_str
else:
pass
但是,它不起作用。对于monster
的预期输出将是nothing。你知道吗
使用
return
:对于列表理解:
就像一个小小的复活节彩蛋,我想我也应该把这个小宝石作为一个选择,如果只是因为你的问题:
使用布尔运算符,可以将
if
行从check()
中完全去掉。你知道吗考虑一下这个
un-pythonic
与否,这是另一个选择。再加上这是他的问题。你知道吗“如果字符串不包含rr,则返回none”
对于那些不知道这是如何工作或为什么工作的人,(和/或喜欢学习很酷的python技巧但不知道这一点)下面是docs页,解释布尔运算符。你知道吗
附言
从技术上讲,它是} ,但是来自
un-pythonic
,因为它是ternary
操作。这确实违背了“Python的禅”~ ^{C
风格的语言,我喜欢它们。相关问题 更多 >
编程相关推荐