Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat individual characters in strings in Python

Tags:

python

string

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"?

like image 584
Jason S Avatar asked Jul 08 '16 18:07

Jason S


People also ask

How do you make a string repeating characters?

Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);

How do you copy a character in a string in Python?

You can use dup1 += char twice in a row instead of dup1 += char + char in the for block, if you prefer it, or possibly if you want to modify the string between duplication.

How do you create a repetition in Python?

Sometimes we need to repeat the string in the program, and we can do this easily by using the repetition operator in Python. The repetition operator is denoted by a '*' symbol and is useful for repeating strings to a certain length.

How do you print special characters multiple times in Python?

Using the * operator to print a character n times in Python In the print() function we can specify the character to be printed. We can use the * operator to mention how many times we need to print this value.


1 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)

like image 88
Bahrom Avatar answered Sep 23 '22 09:09

Bahrom