2014-06-12 124 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)将始终为真。

相关问题