0

所以我想要这样的文字: pretty = [beautiful, attractive, good-looking]

在 python 中,我有来自用户的输入。

UserInput= input()

我想检查 UserInput 是否与列表中的任何单词匹配。如果有匹配项,我想替换与“Pretty”匹配的单词。

我试过这个。


userInput = input()
userInput.split()
for word in userInput:
   if word in pretty:
      userInput.replace(word,"pretty")

这没有任何作用。它不会替换匹配的单词。

如果我有多个列表并想要检查所有列表,还有一个问题。最好的方法是什么?

4

3 回答 3

1

.split()并且不是像on list.replace()这样的就地方法,因为字符串在 python 中是不可变对象,而 list 在 python 中是可变对象。.sort()循环时,您需要拆分,而不是在那之前。此外,您需要重新分配userInput给新字符串,word并被其他子字符串替换。

尝试这个 :

userInput = input()
for word in userInput.split():
   if word in pretty:
      userInput = userInput.replace(word,"pretty")
于 2020-11-21T12:16:40.457 回答
0

简单的enumerate

pretty = ['beautiful', 'attractive', 'good-looking']

userInput = input("Enter the word :")
for i, word in enumerate(pretty):
    if userInput == word:
        pretty[i] = 'pretty'

print(pretty)

测试:

Enter the word :attractive
['beautiful', 'pretty', 'good-looking']
于 2020-11-21T12:52:07.010 回答
0

您必须将 userInput.split() 存储到变量中。.split() 返回一个列表,但不会直接更新 userInput。因为它现在是你的,循环将遍历 userInput 中的每个字符,而不是单词。

所以试试这个

userInput = userInput.split()

当您找到匹配项时,您必须重新分配 userInput 变量。但在你这样做之前,你必须将列表转换回字符串

userInput = " ".join(userInput).replace(word, "pretty")

这对我有用

pretty = ["beautiful", "attractive", "good-looking"]

userInput = input()
userInput = userInput.split()
for word in userInput:
    if word in pretty:
        userInput = " ".join(userInput).replace(word, "pretty")

print(userInput)
于 2020-11-21T12:27:44.507 回答