Home > database >  String slicing in Python for string reversal
String slicing in Python for string reversal

Time:09-07

I want to reverse a string using slicing and initially I tried

string = "abcdef" 
print(string[len(string) - 1: 0: -1])

However this only prints up to the index 1

fedcb

So, I decided to change the slicing by changing the ending index of the slicing to -1

string = "abcdef" 
print(string[len(string) - 1: -1: -1])

I'm assuming this will print up to index 0. But this did not print any characters of the string upon running. My question is why doesn't this work?

CodePudding user response:

for your question,

string = "abcdef" 
print(string[len(string) - 1: -1: -1])

returns an empty string since it's taking the second argument as the stopping point : which is exactly the last character that's why it's empty ,

you can test it by running :

    string = "abcdef" 
    print(string[len(string) - 1: -2: -1])

it only returns the character 'f' xhich is the last character .

Now for what you're trying to achieve : you can either use :

string = "abcdef" 
print(string[-1: -len(string)-1: -1])
##or 
print(string[::-1])

CodePudding user response:

from the docs slice:

 class slice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None.

you can use the [::-1] index to do that

>>> s = 'hello'
>>> s[::-1]
'olleh'

with a negative step, the index will go from -1 to ~(len(s)-1), and by that I mean that the string will go from index -1 to 0 reversed

CodePudding user response:

this is what your looking for

string = "abcdef"
print(string[::-1])
  • Related