Python - 使用for循环创建字符串

3
作为 Python 的初学者,老师布置了这些任务给我完成,但我卡在其中一个上了。它是关于使用 for 循环查找单词中的辅音并创建一个包含这些辅音的字符串。
我现有的代码如下:
consonants = ["qwrtpsdfghjklzxcvbnm"]
summer_word = "icecream"

new_word = ""

for consonants in summer_word:
    new_word += consonants

ANSWER = new_word

我理解for循环,但是我不太懂字符串拼接。如果我使用new_word = [],它就变成了一个列表,所以我应该使用""吗?如果你要连接一些字符串或字符,它应该会变成一个字符串,对吗?如果你有一个整数,你必须使用str(int)来将其连接起来。但是,如何创建这个辅音字母的字符串呢?我认为我的代码没问题,但它没有实现预期的效果。
谢谢。
5个回答

4
你现在的循环只是遍历了夏天单词中的每个字符。你在“for consonants...”语句中给出的“consonants”只是一个虚拟变量,它并没有实际引用你定义的辅音字母。尝试使用类似以下的代码:
consonants = "qwrtpsdfghjklzxcvbnm" # This is fine don't need a list of a string.
summer_word = "icecream"

new_word = ""

for character in summer_word: # loop through each character in summer_word
    if character in consonants: # check whether the character is in the consonants list
        new_word += character
    else:
        continue # Not really necessary by adds structure. Just says do nothing if it isn't a consonant.

ANSWER = new_word

1
Python中的字符串已经是字符列表,可以像处理列表一样处理它们:
In [3]: consonants = "qwrtpsdfghjklzxcvbnm"

In [4]: summer_word = "icecream"

In [5]: new_word = ""

In [6]: for i in summer_word:
   ...:     if i in consonants:
   ...:         new_word += i
   ...:

In [7]: new_word
Out[7]: 'ccrm'

1

您说得对,如果该字符是数字,则必须使用str(int)将其转换为字符串类型。

consonants = ["qwrtpsdfghjklzxcvbnm"]
summer_word = "icecream"

new_word = ""
vowels = 'aeiou'
for consonants in summer_word:
    if consonants.lower() not in vowels and type(consonants) != int:
        new_word += consonants
answer = new_word

在这个for循环中,您正在评估'consonants'是否不是元音字母且不是整数。希望这能帮到您。


0
consonants = "qwrtpsdfghjklzxcvbnm"
summer_word = "icecream"

new_word = ""


for letter in summer_word:
    if letter in consonants:
      new_word += letter

print(new_word)

一个更短的版本可以是
consonants = "qwrtpsdfghjklzxcvbnm"
summer_word = "icecream"

new_word = ""

new_word = [l for l in summer_word if l in consonants]
print("".join(new_word))

0
你在这里遇到的问题是你将变量consonants创建为一个包含字符串的列表。所以去掉方括号,它就会正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接