Python replace function [replace once]

前端 未结 6 1561
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 12:40

I need help with a program I\'m making in Python.

Assume I wanted to replace every instance of the word \"steak\" to \"ghost\" (just go wit

6条回答
  •  猫巷女王i
    2020-12-01 12:46

    Rename one of the words to a temp value that doesn't occur in the text. Note this wouldn't be the most efficient way for a very large text. For that a re.sub might be more appropriate.

     s="The scary ghost ordered an expensive steak"
     print s
     s=s.replace("steak","temp")
     s=s.replace("ghost","steak")
     S=s.replace("temp","steak")
     print s
    

提交回复
热议问题