[英]Python - Create string with for-loop
作為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)
來進行連接。 但是,如何創建這串輔音呢? 我認為我的代碼是正確的,但無法播放。
問候
您的循環當前僅循環遍歷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
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'
沒錯,如果字符是數字,則必須使用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。 希望這對您有所幫助。
這里的問題是,您已將變量輔音創建為列表,其中包含字符串。 因此,刪除方括號,它應該可以工作
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.