How to repeat individual characters in strings in Python

What about:

>>> s = '123abc'
>>> n = 3
>>> ''.join([char*n for char in s])
'111222333aaabbbccc'
>>> 

(changed to a list comp from a generator expression as using a list comp inside join is faster)


If you want to repeat individual letters you can just replace the letter with n letters e.g.

>>> s = 'abcde'
>>> s.replace('b', 'b'*5, 1)
'abbbbbcde'

Or another way to do it would be using map:

"".join(map(lambda x: x*7, "map"))

An alternative itertools-problem-overcomplicating-style option with repeat(), izip() and chain():

>>> from itertools import repeat, izip, chain
>>> "".join(chain(*izip(*repeat(s, 2))))
'112233aabbcc'
>>> "".join(chain(*izip(*repeat(s, 3))))
'111222333aaabbbccc'

Or, "I know regexes and I'll use it for everything"-style option:

>>> import re
>>> n = 2
>>> re.sub(".", lambda x: x.group() * n, s)  # or re.sub('(.)', r'\1' * n, s) - thanks Eduardo
'112233aabbcc'

Of course, don't use these solutions in practice.

Tags:

Python

String