使用Python中的尾随逗号连接或打印列表元素

sam*_*sam 9 python string join list

我有一个列表:

>>> l = ['1', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)

如果我使用join语句,

>>> s = ', '.join(l)
Run Code Online (Sandbox Code Playgroud)

会给我输出为:

'1, 2, 3, 4'
Run Code Online (Sandbox Code Playgroud)

但是,我要做的事如果我想要输出为:

'1, 2, 3, 4,'
Run Code Online (Sandbox Code Playgroud)

(我知道我可以使用字符串连接,但我想知道一些更好的方法)

.

Tad*_*eck 13

字符串连接是最好的方法:

l = ['1', '2', '3', '4']  # original list
s = ', '.join(l) + ','
Run Code Online (Sandbox Code Playgroud)

但你还有其他选择:

  1. 映射到以逗号结尾的字符串,然后加入:

    l = ['1', '2', '3', '4']  # original list
    s = ' '.join(map(lambda x: '%s,' % x, l))
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将空字符串附加到联接列表(不要修改原始l列表!):

    l = ['1', '2', '3', '4']  # original list
    s = ', '.join(l + ['']).rstrip(' ')
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用字符串格式代替串联:

    l = ['1', '2', '3', '4']  # original list
    s = '%s,' % (', '.join(l))
    
    Run Code Online (Sandbox Code Playgroud)


Bou*_*oud 6

如果您使用的是Python 3,则可以利用print内置函数:

print(*l, sep=', ', end=',')
Run Code Online (Sandbox Code Playgroud)
  • *l 解压缩元素列表以将它们作为单独的参数传递给print
  • sep是一个可选参数,设置在从元素打印的元素之间,这里我', '根据需要将其设置为空格
  • end是一个可选参数,将在结果打印字符串的和处推送.我把它设置为','没有空间来满足你的需要

您可以通过导入打印功能从Python 2.6开始使用它

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

然而,这种方式有几点需要注意:

  • 这假设你想在stdout中输出结果字符串; 或者您可以将带有file可选参数的文件中的输出重定向到文件中
  • 如果您使用的是Python 2,则__future__导入可能会破坏代码兼容性,因此如果代码的其余部分不兼容,则需要在单独的模块中隔离代码.

长话短说,无论是这种方法还是其他提出的答案都是很多努力,试图避免+','join结果字符串的末尾添加一个


Mic*_*ild 5

为了str.join()工作,可迭代对象(即此处的列表)中包含的元素本身必须是字符串。如果您想要尾随逗号,只需在列表末尾添加一个空字符串即可。

编辑:稍微充实一下:

l = map(str, [1,2,3,4])
l.append('')
s = ','.join(l) 
Run Code Online (Sandbox Code Playgroud)