how do I do this with sliced notation?
ex. "Hello" to "HHeelloo"
how do I do this with sliced notation?
ex. "Hello" to "HHeelloo"
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")
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
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'
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)
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)
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