-3

how do I do this with sliced notation?

ex. "Hello" to "HHeelloo"

  • 1
    Does this answer your question? [How to repeat individual characters in strings in Python](https://stackoverflow.com/questions/38273353/how-to-repeat-individual-characters-in-strings-in-python) – Gino Mempin Sep 06 '22 at 10:55

7 Answers7

1

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")
lumbric
  • 7,644
  • 7
  • 42
  • 53
1

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
0

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])
  • I am just starting a course fundamentals in Python and we haven't yet reached functions of this kind. I would like to understand how to do this with slice notation. – Peter Stoyanov Sep 05 '22 at 11:16
0
Word = 'Hello'
number_of_time = 2
''.join([char*number_of_time for char in Word])

Output:

'HHeelllloo'
R. Baraiya
  • 1,490
  • 1
  • 4
  • 17
0

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)
Noob Master
  • 91
  • 1
  • 10
0

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)
Sajad
  • 182
  • 1
  • 11
0

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
Ritik Banger
  • 2,107
  • 5
  • 25