close

How to repeat individual characters in strings in Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to repeat individual characters in strings in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to repeat individual characters in strings in Python?

  1. How to repeat individual characters in strings in Python?

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

  2. repeat individual characters in strings in Python

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

Method 1

What about:

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

Method 2

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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read