【问题标题】:Concatenate letter to a string with for loop使用 for 循环将字母连接到字符串
【发布时间】:2014-08-02 13:55:37
【问题描述】:
我想创建一个 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 循环连接?
请帮忙!
问候..!
【问题讨论】:
标签:
python
for-loop
python-3.x
concatenation
【解决方案1】:
这是因为您在每次迭代时将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
【解决方案2】:
您正在将count 重置为循环开始时的空字符串。将count='' 放在for 循环之前。
您的代码的其他问题:您的函数没有返回值,代码缺少缩进,== True 部分已过时。此外,words.split() 仅在 words 是字符串时才有效 - 在这种情况下,isinstance(i, str) 将始终为真。