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"
?
Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With