我正在处理一些字符串,并使用replace()
从中删除一些字符,例如:
a = 'monsterr'
new_a = a.replace("rr", "r")
new_a
然而,假设现在我收到以下字符串:
In:
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
的预期输出将为零。
使用return
:
def check(a_str):
if 'rr' in a_str:
a_str = a_str.replace("rr", "r")
return a_str
列表理解:
a = ["difference", "hinderr"]
x = [i.replace("rr", "r") for i in a]
就像一个小的复活节彩蛋,我想我也会把这个小宝石作为一个选项,如果只是因为你的问题:
如果我的字符串不包含rr,我怎么能不返回?有没有什么只通过或不返回的?
使用布尔运算符,可以完全从check()
中取出if
行。
def check(text, dont_want='rr', want='r'):
replacement = text.replace(dont_want, want)
return replacement != text and replacement or None
#checks if there was a change after replacing,
#if True: returns replacement
#if False: returns None
test = "differrence"
check(test)
#difference
test = "difference"
check(test)
#None
不管是否考虑这个un-pythonic
,它是另一个选项此外,这也是他的问题。
"如果字符串不包含rr,则返回none">
对于那些不知道这是如何或为什么工作的人,(和/或喜欢学习很酷的python技巧,但不知道这一点(,下面是解释布尔运算符的文档页面。
p.S.
从技术上讲,它是un-pythonic
,因为它是一个ternary
操作。这确实违背了"Python的禅宗"~import this
,但来自C
风格的语言,我喜欢它们