簡體   English   中英

Python列表加入-在開始或結尾處包含分隔符

[英]Python list joining — include separator at the start or at the end

', '.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, 

沒有標准方法,但是自然的方法是在末尾或開頭(或末尾開頭)添加空字符串。 使用一些更現代的語法:

>>> ', '.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,'

方法如下:

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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM