我想创建一个 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 循环连接起来?
请帮忙!
问候..!
最佳答案
这是因为您在每次迭代时将 count
设置为 ''
,因此该行应该位于外部:
count = ''
for ...:
另外,你也可以这样做
if isinstance(i, str):
没有必要与 == True
进行比较,因为 isinstance
返回一个 bool 值。
使用您的代码,您将始终得到一个充满 k
的字符串。 为什么?因为 words.split()
将返回字符串列表,因此 if
将始终为 True
.
如何解决这个问题?您可以使用 try- except
block :
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
关于python - 使用 for 循环将字母连接到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24181045/