2014-06-12 67 views
2

我想創建一個for循環,它將檢查列表中的項目,如果滿足條件,則每次都會向字符串添加一個字母 。使用for循環將字母連接到字符串

這是我編:

words = 'bla bla 123 554 gla gla 151 gla 10' 

def checkio(words): 
for i in words.split(): 
    count = '' 
    if isinstance(i, str) == True: 
     count += "k" 
    else: 
     count += "o" 

我應該算的結果是 'kkookkoko'(5次因5串)。

我從這個函數得到的是count ='k'。

爲什麼字母不能通過我的for循環連接?

請幫忙!

問候..!

回答

4

這是因爲你在每次迭代設置count'',該行應外:

count = '' 
for ...: 

而且,你可以做

if isinstance(i, str): 

它沒有必要用== True比較,因爲isinstance返回布爾值

隨着你的代碼,你總是會得到一個完整的k字符串。 爲什麼?由於words.split()將返回一個字符串列表,因此if將始終爲True

你如何解決它?您可以使用try-except塊:

def checkio(words): 
    count = '' 
    for i in words.split(): 
     try: # try to convert the word to an integer 
      int(i) 
      count += "o" 
     except ValueError as e: # if the word cannot be converted to an integer 
      count += "k" 
    print count 
1

您重置count是在每次循環開始的空字符串。在for循環之前放入count=''。 代碼的其他問題:函數沒有返回值,代碼缺少縮進,== True部分已過時。如果words是一個字符串,那麼words.split()也只能工作 - 在這種情況下,isinstance(i, str)將始終爲真。

相關問題