How to double the strings in Python ex. "Hello" to "HHeelllloo"

Question:

how do I do this with sliced notation?

ex. "Hello" to "HHeelloo"

Asked By: Peter Stoyanov

||

Answers:

You can use join function and for loop to an empty string. The letters will be double of all letters.

s="Hello"
"".join([x*2 for x in s])
Word = 'Hello'
number_of_time = 2
''.join([char*number_of_time for char in Word])

Output:

'HHeelllloo'
Answered By: Stackpy

You can iterate through the input string, then use the multiplication operator to duplicate the string and then concatenate again using join():

"".join(2 * s for s in "Hello")
Answered By: lumbric

You could simply loop each letter in your string and add it twice to a new string. For example

word = "Hello"
doubledWord = ""
for letter in word:
    doubledWord += letter * 2

print(doubledWord)

Output

HHeelllloo
Answered By: Gustav Lindahl

First, shouldn’t it be "HHeelllloo"? or you don’t want to duplicate a character if it’s already duplicated? I will give both answers.

Also, using the slice notation? that will be a bit convoluted. But here you go:

text = "Hello"
result = ""

Duplicating all characters:

for i in range(len(text)):
    result += 2 * (text[i:i+1])

Only one duplicate:

for i in range(len(text)):
    if text[i] not in text[0:i]:
        result += 2 * (text[i:i+1])

But there is absolutely no need or the slicing, text[i] is sufficient.

Answered By: mudlej

you can achieve it by iterating the whole string and at each iteration multiply the string by 2

str1 = 'Hello'
str2= ''
for i in range(len(str1)):

    str2 += str1[i]*2

print(str2)
Answered By: Noob Master

Using sliced notation in a non-trivial manner:

s = "Sajad"
s2 = 2 * "Sajad"
ss = ""
for i in range(len(s)):
    ss += s2[i::len(s)]
print(ss)
Answered By: Sajad

The term slicing in programming usually refers to obtaining a substring, sub-tuple, or sublist from a string, tuple, or list respectively. You cannot slice a string to double every character. Though you can use sliced notation- method 6. Here are some methods to get the desirable output.

Method 1:

input = Hello
output=""
for i in input:
    output = output + i*2
print(output)  

Method 2:

"".join(2 * i for i in "Hello")

Method 3:

s='Hello'
from itertools import chain,izip
''.join(chain(*izip(s,s)))

Method 4:

s.translate({ord(x):2*x for x in set(s)})

Method 5:

s = "Hello"
import re
re.sub('(.)', r'1' * 2, s)

Method 6 (using sliced notation):

s = "Hello"
s1 = 2 * s
s2 = ""
for i in range(len(s)):
    s2 += s1[i::len(s)]
print(s2)

All would result in:

HHeelllloo
Answered By: Ritik Banger
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.