Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding characters to a string in python 3

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?

like image 438
Matt Avatar asked Mar 08 '11 21:03

Matt


People also ask

How do I add characters to a string in Python?

In Python, the string is an immutable object. You can use the '+' operator to append two strings to create a new string.

How do you add characters to a 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.

Can you add chars in Python?

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.


2 Answers

>>> ' '.join('abcdefg')
'a b c d e f g'
like image 175
poke Avatar answered Nov 07 '22 20:11

poke


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.

like image 37
dawg Avatar answered Nov 07 '22 20:11

dawg