如何使用replace函数完全替换字符串而不是字符串的一部分?

时间:2019-06-26 04:35:31

标签: python

我是Python的绝对初学者。我正在创建一个疯狂的lib游戏,该游戏使用replace函数替换模板中的单词。由于未根据用户输入更改模板,因此以下代码无法提供正确的输出。

#!/usr/bin/env python
print("lets play a game of mad libs")
print("you will be asked for a word such as noun,adjective,etc.enter the specified word")

template="""I can't believe its already word1! I can't wait to 
put on my word 2 and visit every word3 in my neighbourhood.
This year,I am going to dress up as word4 with word5 word6.
Before I word7,I make sure to grab my word8 word9 to hold all 
of my word10.
Happy word11!"""

word1=input("enter a  holiday")
word2=input("enter a noun")
word3=input("enter a place")
word4=input("enter a person")
word5=input("enter a adjective")
word6=input("enter  body part (plural)")
word7=input("enter a verb")
word8=input("enter a adjective")
word9=input("enter a noun")
word10=input("enter  food")
word11=input("enter a holiday")
template=template.replace("word1",word1)
template=template.replace("word2",word2)
template=template.replace("word3",word3)
template=template.replace("word4",word4)
template=template.replace("word5",word5)
template=template.replace("word6",word6)
template=template.replace("word7",word7)
template=template.replace("word8",word8) 
template=template.replace("word9",word9)
template=template.replace("word10",word10)
template=template.replace("word11",word11)
print(template)

我知道我可以使用流控制循环,但我只是了解字符串操作。所以请原谅我的代码混乱。

输出的问题是,替换功能用“ word1”的相同输入替换“ word1”,“ word10”和“ word11”,因为“ word1”是二者的一部分。总之有避免这种情况的方法,而不仅仅是更改名称如果是“ word10”和“ word11”,则应使用哪种替代功能?

5 个答案:

答案 0 :(得分:2)

默认情况下,string.replace()将替换所有匹配的匹配项。这就是word1word1word10word11匹配的原因。

如果您真的想学习replace函数,它需要一个可选参数 count

string.replace(oldvalue, newvalue, count)

因此,如果单词是连续的,则可以尝试以下行:

template=template.replace("word_x",word_x, 1)

这样,每次调用replace()时,它只会替换第一次出现的情况。

另一种方法(假设您顺序输入)是使用字符串占位符%s

例如,如果我们要使用11个用户输入字符串,然后将它们连接到一个长字符串:

s = (" ".join(["%s" for i in range(11)]) % tuple([input("Input %d: " % (i+1)) for i in range(11)]))

具体来说,应该是:

template="""I can't believe its already %s! I can't wait to
put on my %s and visit every %s in my neighbourhood.
This year,I am going to dress up as %s with %s %s.
Before I %s,I make sure to grab my %s %s to hold all
of my %s.
Happy %s!"""  # there're 11 placeholders '%s'

word1=input("enter a  holiday")
word2=input("enter a noun")
word3=input("enter a place")
word4=input("enter a person")
word5=input("enter a adjective")
word6=input("enter  body part (plural)")
word7=input("enter a verb")
word8=input("enter a adjective")
word9=input("enter a noun")
word10=input("enter  food")
word11=input("enter a holiday")

user_inputs = (word1, word2, word3, word4, word5, word6, 
               word7, word8, word9, word10, word11)  # length of this tuple is 11

print(template % user_inputs)

希望这会有所帮助。

答案 1 :(得分:1)

使用正则表达式替换而不是“简单”字符串替换。正则表达式使您可以指示要在单词边界处进行匹配。这样可以很好地解决您的问题。例如:

import re

str = "word1 word2 word3...word11, word12...word123...word1"

str = re.sub(r'\bword1\b', '_replacement1_', str)
str = re.sub(r'\bword12\b', '_replacement12_', str)

print(str)

结果:

_replacement1_ word2 word3...word11, _replacement12_...word123..._replacement1_

请注意,两个替换都不会触及word123,并且在输入的开头和结尾都替换了word1,这意味着替换确实愿意进行多次替换。

答案 2 :(得分:1)

您可以做的一件事情不是使用replace()方法,而是使用format()方法设置字符串格式并使用命名参数(请注意,template中的花括号{}和在其中要替换的参数名称):

template="""I can't believe its already {word1}! I can't wait to
put on my {word2} and visit every {word3} in my neighbourhood.
This year,I am going to dress up as {word4} with {word5} {word6}.
Before I {word7},I make sure to grab my {word8} {word9} to hold all
of my {word10}.
Happy {word11}!"""

word1 = 'abc1'
word2 = 'abc2'
word3 = 'abc3'
word4 = 'abc4'
word5 = 'abc5'
word6 = 'abc6'
word7 = 'abc7'
word8 = 'abc8'
word9 = 'abc9'
word10 = 'abc10'
word11 = 'abc11'

template = template.format(
    word1=word1,
    word2=word2,
    word3=word3,
    word4=word4,
    word5=word5,
    word6=word6,
    word7=word7,
    word8=word8,
    word9=word9,
    word10=word10,
    word11=word11
)

print(template)

打印:

I can't believe its already abc1! I can't wait to
put on my abc2 and visit every abc3 in my neighbourhood.
This year,I am going to dress up as abc4 with abc5 abc6.
Before I abc7,I make sure to grab my abc8 abc9 to hold all
of my abc10.
Happy abc11!

答案 3 :(得分:1)

基于Andrej Kesely的答案,一种更优雅的方法是使用f-strings(假设您正在运行Python> = 3.6)。

word1=input("enter a holiday")
word2=input("enter a noun")
word3=input("enter a place")
word4=input("enter a person")
word5=input("enter a adjective")
word6=input("enter body part (plural)")
word7=input("enter a verb")
word8=input("enter a adjective")
word9=input("enter a noun")
word10=input("enter food")
word11=input("enter a holiday")

template=f"""I can't believe its already {word1}! I can't wait to
put on my {word2} and visit every {word3} in my neighbourhood.
This year,I am going to dress up as {word4} with {word5} {word6}.
Before I {word7},I make sure to grab my {word8} {word9} to hold all
of my {word10}.
Happy {word11}!"""

print(template)

请注意字符串文字前的f –这表示它是格式化的字符串。

答案 4 :(得分:0)

以相反的顺序替换,最长到最短。 word11只能替换word11word10只能替换word10,并且到word1出现时,将没有任何word10word11可以混在一起。

或者,切换到正则表达式,使用单词边界\b解决一个问题,然后再考虑十二个新问题。