', '.join(['a', 'b', 'c', 'd'])
的输出是:
a, b, c, d
Python中是否有标准方法来实现以下输出?
# option 1, separator is also at the start
, a, b, c, d
# option 2, separator is also at the end
a, b, c, d,
# option 3, separator is both at the start and the end
, a, b, c, d,
答案 0 :(得分:4)
没有标准方法,但是自然的方法是在结尾或开头(或结尾和开头)添加空字符串。使用一些更现代的语法:
>>> ', '.join(['', *['a', 'b', 'c', 'd']])
', a, b, c, d'
>>> ', '.join([*['a', 'b', 'c', 'd'], ''])
'a, b, c, d, '
>>> ', '.join(['', *['a', 'b', 'c', 'd'], ''])
', a, b, c, d, '
或者仅使用字符串格式:
>>> sep = ','
>>> data = ['a', 'b', 'c', 'd']
>>> f"{sep}{sep.join(data)}"
',a,b,c,d'
>>> f"{sep.join(data)}{sep}"
'a,b,c,d,'
>>> f"{sep}{sep.join(data)}{sep}"
',a,b,c,d,'
答案 1 :(得分:0)
这是方法:
list1 = ['1','2','3','4']
s = ","
r = f"{s}{s.join(list1)}"
p = f"{s.join(list1)}{s}"
q = f"{s}{s.join(list1)}{s}"
print(r)
print(p)
print(q)