How to repeat single characters in strings in Python

I know that

"123abc" * 2 

evaluated as "123abc123abc" , but there is an easy way to repeat individual letters N times, for example. convert "123abc" to "112233aabbcc" or "111222333aaabbbccc" ?

+8
source share
9 answers

What about:

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

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

+19
source

An alternative itertools option itertools problem overriding style 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 regular expressions, and I will use it for everything" - a 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, do not use these solutions in practice.

+4
source

Or another way to do this would be to use map :

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

And since I use numpy for everything, here we go:

 import numpy as np n = 4 ''.join(np.array(list(st*n)).reshape(n, -1).T.ravel()) 
+2
source

If you want to repeat individual letters, you can simply replace the letter with n letters, for example.

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

@ The answer to the question is probably clearer than mine, but just to say that there are many solutions to this problem:

 >>> s = '123abc' >>> n = 3 >>> reduce(lambda s0, c: s0 + c*n, s, "") '111222333aaabbbccc' 

Note that reduce not built-in in python 3, and you should use functools.reduce .

+1
source

Or using regular expressions:

 >>> import re >>> s = '123abc' >>> n = 3 >>> re.sub('(.)', r'\1' * n, s) '111222333aaabbbccc' 
+1
source

Another way:

 def letter_repeater(n, string): word = '' for char in list(string): word += char * n print word letter_repeater(4, 'monkeys') mmmmoooonnnnkkkkeeeeyyyyssss 
+1
source

here is my naive decision

 text = "123abc" result = '' for letters in text: result += letters*3 print(result) 

output: 111222333aaabbbccc

+1
source

All Articles