【问题标题】:String replace() is not working as expected字符串替换()没有按预期工作
【发布时间】:2019-08-01 10:05:21
【问题描述】:

我在使用 python 中的 replace() 函数时遇到了一些问题。这是我的代码:

string = input()
word = string.find('word')
if word >= 1:
    string = string.replace('word', 'word.2')
print(string)

输出给出word。不应该是word.2吗? 我糊涂了。有什么帮助吗?

编辑:在玩了一会儿这个问题之后,我发现现在的问题是“为什么 string.find('word') 等于 0 对于输入 word

【问题讨论】:

  • 我在使用 Python 3 的机器上运行,但没有发现任何问题。
  • 您使用的是什么版本的python,当这不起作用时您正在测试什么输入?这在 python 3.7 上按预期工作
  • 我已经在我的回答中回答了您的“已编辑”问题。看看吧。

标签: python replace find


【解决方案1】:

无需使用查找功能,只需:

string = input()
string = string.replace('word', 'word.2')

但是,如果我在 Python3 中运行它,您的代码是正确的 ;-) 您的输入看起来如何?

【讨论】:

    【解决方案2】:

    代替

    word >= 1
    

    word >= 0
    

    string.find() 返回单词的第一次出现。如果你的字符串是 'word' 并且你找到 'word',它会返回 0,因为单词 'word' 首先出现在索引 0 处。

    在 python 中,数组从 0 开始。字符串中的第一个字符在索引 0 处。

    因此,'word'中的'word'在第一个位置,即0。

    【讨论】:

      【解决方案3】:

      这是因为第一次出现被视为零位置,请使用下面的代码

      string = input().replace('word','word.2')
      print(string)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-31
        • 2015-02-22
        • 2012-06-17
        • 2018-11-12
        • 1970-01-01
        • 1970-01-01
        • 2020-03-09
        • 2023-04-01
        相关资源
        最近更新 更多