gpt4 book ai didi

python - 使用 for 循环将字母连接到字符串

转载 作者:行者123 更新时间:2023-11-28 21:54:27 24 4
gpt4 key购买 nike

我想创建一个 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 返回一个 boolean

使用您的代码,您将始终得到一个充满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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com