如何正确地将字符串文字连接到字符串变量并重新分配给变量

How to properly concatenate string literal to string variable and reassign to variable

我正在尝试将字符串文字连接到字符串变量并将该值重新分配给同一个变量。

我试过 += 运算符和

之类的东西
string = string + "another string"

但这不起作用。

这是我的代码。

userWord = input("Enter a word: ").upper()

# Prompt the user to enter a word and assign it to the userWord variable


for letter in userWord:
    # Loops through userWord and concatenates consonants to wordWithoutVowels and skips vowels
    if letter == "A" or letter == "E" or letter == "I" or letter == "O" or letter == "U":
        continue
    wordWithoutVowels += userWord # NameError: name "wordWithoutVowels" is not defined

print(wordWithoutVowels)

首先,我认为您打算 wordWithoutVowels += letter,而不是整个 userWord。其次,该表达式与 wordWithoutVowels = wordWithoutVowels + userWord 相同,这意味着 wordWithoutVowels 需要在它之前定义。

只需在for循环

之前添加以下内容
wordWithoutVowels = ''

编辑:

如@DeveshKumarSingh 所述,您可以使用以下 if 条件而不是使用 continue

来进一步改进循环
if letter not in ['A','E','I','O','U']:
    wordWithoutVowels += letter 

您的代码存在一些问题

  • 您没有在 for 循环之前初始化 wordWithoutVowels。您需要使用 wordWithoutVowels = ''

  • 可以使用in运算符检查字母是否不存在于元音字母中,然后只更新结果字符串

更新后的代码将是

userWord = input("Enter a word: ").upper()

#Initialize wordWithoutVowels
wordWithoutVowels = ''
for letter in userWord:
    #If letter does not fall in vowels, append that letter
    if letter not in ['A','E','I','O','U']:
        wordWithoutVowels += letter 

print(wordWithoutVowels)

输出将是

Enter a word: hello world
HLL WRLD