How to repeat individual characters in strings in Python

Question:

I know that

"123abc" * 2

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

Asked By: Jason S

||

Answers:

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)

Answered By: Bahrom

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.

Answered By: alecxe

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'
Answered By: ssmid

@Bahrom’s answer 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 is not a built-in in python 3, and you have to use functools.reduce instead.

Answered By: julienc

Or using regular expressions:

>>> import re
>>> s = '123abc'
>>> n = 3
>>> re.sub('(.)', r'1' * n, s)
'111222333aaabbbccc'
Answered By: Eduardo Cuesta

Another way:

def letter_repeater(n, string):
    word = ''
    for char in list(string):
        word += char * n
    print word

letter_repeater(4, 'monkeys')


mmmmoooonnnnkkkkeeeeyyyyssss
Answered By: af3ld

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())
Answered By: Gerges

Or another way to do it would be using map:

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

here is my naive solution

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

print(result)

output:
111222333aaabbbccc

Answered By: khappe khappe

Python:

def  LetterRepeater(times,word) :
    word1=''
    for letters in word:
        word1 += letters * times
    print(word1)

    word=input('Write down the word :   ')
    times=int(input('How many times you want to replicate the letters ?    '))
    LetterRepeater(times,word)
Answered By: Ata Reenes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.