pythonslicenotation

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


how do I do this with sliced notation?

ex. "Hello" to "HHeelloo"


Solution

  • 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