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

时间:2018-09-16 12:09:31

标签: python for-loop concatenation

作为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)来进行连接。 但是,如何创建这串辅音呢?我认为我的代码不错,但无法播放。

致谢

5 个答案:

答案 0 :(得分: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 :(得分: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'

答案 2 :(得分:1)

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

let material = SCNMaterial()

material.diffuse.contents = UIImage(named: "Albedo.png")
material.ambientOcclusion.contents = UIImage(named: "AO.png")
material.normal.contents = UIImage(named: "Normals.png")

在for循环中,您正在评估'辅音'不是元音也不是int。希望对您有帮助。

答案 3 :(得分:0)

这里的问题是,您已将变量辅音创建为列表,其中包含字符串。所以去掉方括号就可以了

答案 4 :(得分: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))