【问题标题】:How to properly concatenate string literal to string variable and reassign to variable如何正确地将字符串文字连接到字符串变量并重新分配给变量
【发布时间】:2019-05-26 16:31:08
【问题描述】:

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

我试过+= 运算符和类似的东西

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)

【问题讨论】:

    标签: python python-3.x string-concatenation


    【解决方案1】:

    首先,我认为你打算做wordWithoutVowels += letter,而不是整个userWord。其次,那个表达式和wordWithoutVowels = wordWithoutVowels + userWord是一样的,也就是说wordWithoutVowels需要在它前面定义。

    只需在 for 循环之前添加以下内容

    wordWithoutVowels = ''
    

    编辑:

    正如@DeveshKumarSingh 提到的,您可以通过使用以下if 条件而不是使用continue 来进一步改进循环

    if letter not in ['A','E','I','O','U']:
        wordWithoutVowels += letter 
    

    【讨论】:

    • 你说得对,我忘了添加wordWithoutVowels = "",并不是要连接整个userWord,但重新运行它会引发同样的错误。
    • 您能更新问题中的代码吗?因为它适合我
    • 你是对的。我已经更新了我的问题(代码现在运行)
    • 我的意思是如果它不起作用就更新。您的问题现在有正确的代码,但没有发生错误。请还原该编辑,并将此答案标记为已接受,因为它对您有用。
    【解决方案2】:

    您的代码存在一些问题

    • 您没有在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2019-08-19
      相关资源
      最近更新 更多