【问题标题】:Why isn't this Python replace function working? [duplicate]为什么这个 Python 替换函数不起作用? [复制]
【发布时间】:2014-11-13 18:23:21
【问题描述】:

我正在尝试从较大的字符串中删除一组字符。这是我尝试过的:

string = 'aabc'
remove = 'ac'
for i in remove:
    string.replace(i, '', 1)
print(string)

当我运行它时,我不断取回我的原始字符串。变量i 获取字符'a',然后是'c'。如果我做string.replace('a', '', 1),替换功能对我有用。为什么这不起作用或有更简单的方法可以做到这一点?

【问题讨论】:

  • help(str.replace) --> 返回字符串 S 的副本,其中所有出现的子字符串 old 都替换为 new。如果给定了可选参数 count,则仅替换第一个 count 出现。

标签: python string replace


【解决方案1】:

字符串在python中是不可变的,所以string.replace()不会改变字符串;它返回一个带有替换的新字符串。

试试这个:

string = string.replace(i, '', 1)

【讨论】:

  • 好的,这是有道理的。谢谢。
【解决方案2】:

replace 返回一个新字符串。

python 中的字符串是不可变的。

因此,您必须分配返回值:

string_new = "ABCD".replace("A","Z")

【讨论】:

    【解决方案3】:

    将生成一个新字符串,因为字符串是不可变的...

    试试这个 -

    string = 'aabc'
    remove = 'ac'
    for i in remove:
        result = string.replace(i, '', 1)
    print(result)
    

    【讨论】:

      【解决方案4】:

      由于字符串是不可变的,因此您不能仅将 replacestring.replace() 一起使用。 作为更好的方式使用set

      >>> s='aabcc'
      >>> s=''.join(set(s))
      'acb'
      

      【讨论】:

        猜你喜欢
        • 2013-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-18
        • 2021-04-06
        • 2015-06-10
        • 1970-01-01
        相关资源
        最近更新 更多