首页 > 解决方案 > Python逗号用于循环条件逗号分隔

问题描述

我想,当我for循环时,每个项目的末尾都会有逗号,除了最后一项,最后一项应该是点

x = ['df', 'second', 'something', 'another']

separator = ''
for i in x:

  r = i
  print(r, separator)
  separator = ','
else:
  separator = '.'

这是我当前的代码。

我的预期结果应该如下所示:

df,
second ,
something ,
another.

在这种情况下谁能帮助我?

标签: pythonpython-3.x

解决方案


使用enumerate

前任:

x = ['df', 'second', 'something', 'another']
l = len(x)-1
for i, v in enumerate(x):
    if i != l:
        print(v, ",")
    else:
        print(v.strip()+".")

输出:

df ,
second ,
something ,
another.

或者如果你想在单行逗号分隔使用它

print(", ".join(x) + ".") # -->df, second, something, another.

推荐阅读