首页 > 解决方案 > 如何使用替换功能来完全替换字符串而不是它的一部分?

问题描述

我是 Python 的绝对初学者。我正在创建一个疯狂的 lib 游戏,它使用替换函数来替换模板中的单词。以下代码没有给出正确的输出,因为模板没有根据用户输入进行更改。

#!/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”。如果没有,应该使用什么替代功能?

标签: python

解决方案


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

如果您真的想学习替换功能,它需要一个可选参数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)

希望这可以帮助。


推荐阅读