Adding characters to a string in python 3
I currently have a string that I want to edit by adding spaces between each chara开发者_如何学JAVActer, so I currently have s = 'abcdefg'
and I want it to become s = 'a b c d e f g'
. Is there any easy way to do this using loops?
>>> ' '.join('abcdefg')
'a b c d e f g'
You did specify "using loops"
A string in Python is an iterable, meaning you can loop over it.
Using loops:
>>> s = 'abcdefg'
>>> s2=''
>>> for c in s:
... s2+=c+' '
>>> s2
'a b c d e f g ' #note the trailing space there...
Using a comprehension, you can produce a list:
>>> [e+' ' for e in s]
['a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g '] #note the undesired trailing space...
You can use map
:
>>> import operator
>>> map(operator.concat,s,' '*len(s))
['a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g ']
Then you have that pesky list instead of a string and a trailing space...
You could use a regex:
>>> import re
>>> re.sub(r'(.)',r'\1 ',s)
'a b c d e f g '
You can even fix the trailing space with a regex:
>>> re.sub(r'(.(?!$))',r'\1 ',s)
'a b c d e f g'
If you have a list, use join
to produce a string:
>>> ''.join([e+' ' for e in s])
'a b c d e f g '
You can use the string.rstrip()
string method to remove the unwanted trailing whitespace:
>>> ''.join([e+' ' for e in s]).rstrip()
'a b c d e f g'
You can even write to a memory buffer and get a string:
>>> from cStringIO import StringIO
>>> fp=StringIO()
>>> for c in s:
... st=c+' '
... fp.write(st)
...
>>> fp.getvalue().rstrip()
'a b c d e f g'
But since join works on lists or iterables, you might as well use join on the string:
>>> ' '.join('abcdefg')
'a b c d e f g' # no trailing space, simple!
The use of join
in this way is one of the most important Python idioms.
Use it.
There are performance considerations as well. Read this comparison on various string concatenation methods in Python.
Using f-string,
s = 'abcdefg'
temp = ""
for i in s:
temp += f'{i} '
s = temp
print(s)
a b c d e f g
[Program finished]
精彩评论