I currently have a string that I want to edit by adding spaces between each character, 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?
In Python, the string is an immutable object. You can use the '+' operator to append two strings to create a new string.
One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.
To increment a character in a Python, we have to convert it into an integer and add 1 to it and then cast the resultant integer to char. We can achieve this using the builtin methods ord and chr.
>>> ' '.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With