Search code examples
python-3.xstringconcatenation

In a for loop, characters are not getting concatenated to an empty string variable


inp='peter piper picked a peck of pickled peppers.'
mod_str=""
for char in range(-1,-(len(inp)+1)):
    mod_str+=inp[char]

print(mod_str)

The code is giving an empty string as an output, I think the characters are not getting concatenated to the empty string inside the for loop, can you please tell me how to fix this?

I expected the output to be like this:

'.sreppep delkcip fo kcep a dekcip repip retep'

I tried to append the characters from the first negative index from the right to the length of the string to get the output. Since range gives numbers excluding the stop value, I have added +1 to the length value to give it as the stop value for range function(since the negative index numbers of the strings ranges from -1 to -(length of the string)).


Solution

  • the range function in python actually takes three parameters

    it's definition can be referred to as below:

    def range(start, end, step=1)
    

    if you want range to take step backward in the domain you specify it you should provide a -1 step so that the modified code looks like this:

    inp = 'peter piper picked a peck of pickled peppers.'
    mod_str = ""
    for char in range(-1, -(len(inp)+1), -1):
        mod_str += inp[char]
    
    print(mod_str)
    

    you can also use slicing to reverse a string which is similar to range:

    inp = 'peter piper picked a peck of pickled peppers.'
    mod_str = inp[::-1]
    print(mod_str)