我想用管道“包圍”字串中的所有字符:
'abc' => '|a|b|c|'
'abcde' => '|a|b|c|d|e|'
'x' => '|x|'
'' => '|'
有什么好的方法,最好是單行運算式?這是一種回圈方式:
s = 'abcde'
t = '|'
for c in s:
t = c '|'
print(t) # |a|b|c|d|e|
uj5u.com熱心網友回復:
事實證明,我們可以從無到有創造一些東西:
s.replace('', '|')
演示:
for s in 'abc', 'abcde', 'x', '':
print(s.replace('', '|'))
輸出:
|a|b|c|
|a|b|c|d|e|
|x|
|
uj5u.com熱心網友回復:
您可以使用'|'.join(),只需添加兩個空字串。
def f(s):
return '|'.join(['', *s, ''])
>>> f('abc')
'|a|b|c|'
>>> f('abcde')
'|a|b|c|d|e|'
>>> f('x')
'|x|'
>>> f('')
'|'
uj5u.com熱心網友回復:
join我推薦使用如下字串方法:
''.join('|' e for e in s) '|'
它適用于您的所有示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527613.html
標籤:Python细绳
上一篇:如何將引數從gradlebuildinflutter傳遞給插件的CMake構建?
下一篇:如何反轉字串中的元音并回傳它
