I want to "surround" all characters in a string with pipes:
'abc' => '|a|b|c|'
'abcde' => '|a|b|c|d|e|'
'x' => '|x|'
'' => '|'
What's a good way to do it, preferably as a one-line expression? Here's a way with a loop:
s = 'abcde'
t = '|'
for c in s:
t = c '|'
print(t) # |a|b|c|d|e|
CodePudding user response:
Turns out we can create something from nothing:
s.replace('', '|')
Demo:
for s in 'abc', 'abcde', 'x', '':
print(s.replace('', '|'))
Output:
|a|b|c|
|a|b|c|d|e|
|x|
|
CodePudding user response:
You can use '|'.join()
, just need to add two null strings.
def f(s):
return '|'.join(['', *s, ''])
>>> f('abc')
'|a|b|c|'
>>> f('abcde')
'|a|b|c|d|e|'
>>> f('x')
'|x|'
>>> f('')
'|'
CodePudding user response:
I recommend using string method join
as follows:
''.join('|' e for e in s) '|'
It works on all of your examples.