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

问题描述 投票:1回答:5

作为Python的初学者,我由老师完成了这些任务,并且我被困在其中一个上面。它是关于使用for循环在一个单词中找到辅音,然后用这些辅音创建一个字符串。

我的代码是:

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

new_word = ""

for consonants in summer_word:
    new_word += consonants

ANSWER = new_word

我得到的for循环,但它是我没有真正得到的连接。如果我使用new_word = []它会成为一个列表,所以我应该使用""?如果你连接了许多字符串或字符,它应该成为一个字符串,对吧?如果你有一个int,你必须使用str(int)来连接它。但是,我如何创建这一串辅音呢?我认为我的代码是合理的,但它没有发挥出来。

问候

python for-loop concatenation
5个回答
2
投票

你的循环当前只是循环遍历summer_word的字符。你在“辅音......”中给出的“辅音”这个名字只是一个虚拟变量,它实际上并没有引用你定义的辅音。尝试这样的事情:

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循环中,你正在评估'辅音'是不是元音而不是int。希望这对你有所帮助。


0
投票

你在这里遇到的问题是你已经将变量辅音创建为一个带有字符串的列表。所以删除方括号,它应该工作


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))
© www.soinside.com 2019 - 2024. All rights reserved.