【问题标题】:how do I replace a string in a phrase in python?如何在python中替换短语中的字符串?
【发布时间】:2021-02-02 19:47:04
【问题描述】:

所以这是我在 pyhton 中编写的代码,由于某种原因它不起作用所以我希望这里的人可以帮助我找到解决方案 * 我只是一个初学者 *

    def replace(phrase):
    replaced = ""
    for word in phrase:
        if word == ("what"):
            replaced = replaced + "the"
        else:
            replaced = replaced + word
    return replaced

    print(replace(input("enter a phrase: ")))

【问题讨论】:

  • 你的 for 循环是 for word in phrase 但是当你迭代一个字符串时,你实际上是在迭代每个字符。一种迭代单词的方法是for word in phrase.split(),它将phrase 用空格分开。
  • 这能回答你的问题吗? Replacing specific words in a string (Python)

标签: python python-3.x


【解决方案1】:

你可以试试这段代码,希望对你有帮助

def replace(phrase):
    phrase = phrase.split()
    replaced = ""
    for word in phrase:
        if word == ("what"):
            replaced = replaced + " the"
        else:
            replaced = replaced +" "+ word
    return replaced[1:]

print(replace(input("enter a phrase: ")))

输出是:

enter a phrase: where what this what when ,
where the this the when ,

【讨论】:

    【解决方案2】:

    在这里,我们使用 .split() 将您的短语按空格分开。结果,您将获得每个单词 ['hi', 'what', 'world'] 的列表。如果你不拆分它,你将遍历每个字符,如果字符串而不是任何字符将等于“what”

     def replace(phrase):
        phrase = phrase.split()
        replaced = ""
        for word in phrase:
            if word == ("what"):
                replaced = replaced + " the "
            else:
                replaced = replaced + word
        return replaced
    
    print(replace(input("enter a phrase: ")))
    

    【讨论】:

      【解决方案3】:

      尝试替换方法:

      def replace(phrase):
        replaced = phrase.replace("what","the")
        return replaced
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多