如何在使用replace()字符串方法时不执行任何操作?

2024-10-01 07:43:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一些字符串,并使用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。你知道吗


Tags: 字符串innewreturnifdefcheckrr
2条回答

使用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]

就像一个小小的复活节彩蛋,我想我也应该把这个小宝石作为一个选择,如果只是因为你的问题:

How can I return nothing if my string doesnt contain rr? Is there anyway of just pass or return nothing?

使用布尔运算符,可以将if行从check()中完全去掉。你知道吗

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技巧但不知道这一点)下面是docs页,解释布尔运算符。你知道吗

附言

从技术上讲,它是un-pythonic,因为它是ternary操作。这确实违背了“Python的禅”~ ^{},但是来自C风格的语言,我喜欢它们。

相关问题 更多 >