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

标签 python for-loop python-3.x concatenation

我想创建一个 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/

相关文章:

python-3.x - Ubuntu 终端从 Anaconda 基础环境开始(如何更正?)

python-3.x - awscli 无法工作 : No module named 'awscli'

Python 中的 C# &&

python - 优化双for循环以查找二维数组上特定值的计数

c++ - 我的列表控件需要一个 while 循环

Python - 缩短冗余循环

python 3 : How to log warnings and errors to log file?

python - Django:更改由 {{variable}} 生成的文本字符串中间的 HTML 模板字体

python - 在 python 中使用外部文件进行测试

python - 在 H5PY 中打开文件时出错(未找到文件签名)