+ 1
Python String question: What does [::-1] mean?
Apparently it reverses the string, but I don't know why.
6 odpowiedzi
+ 5
A slice bracket has three 'slots': Start, end, and step.
[2:17:3] means: Start at 2, end before 17, go in steps of 3.
[17:2:-3] means: Start at 17, end before 2, go *backward* steps of 3.
If you leave slots empty, there's a default.
[:] means: The whole thing.
[::1] means: Start at the beginning, end when it ends, walk in steps of 1 (which is the default, so you don't even need to write it).
[::-1] means: Start at the end (the minus does that for you), end when nothing's left and walk backwards by 1.
+ 3
In list slicing threre are usually 3 factors [x:y:z] x is the starting point, y is the ending point, z is the step taken from x to y. A regular step will be 1 which goes through the list normally, but when it is -1 the list takes it's step backward resulting in a reversed list
+ 3
It is only that one case, though. You quickly remember it and then it's just convenient.
+ 1
In Python, the syntax `[::-1]` is used to reverse a string. It is known as string slicing with a step value of -1.
Let's break down how it works:
- The first colon `:` indicates that we want to slice the entire string.
- The second colon `:` indicates the step value.
- The `-1` as the step value means we want to traverse the string in reverse order, moving from the last character to the first character.
my_string = "Hello, World!"
reversed_string = my_string[::-1]
print(reversed_string)
Output:
!dlroW ,olleH
In this example, `my_string[::-1]` returns a reversed version of the original string. The characters are iterated in reverse order, resulting in the output "!dlroW ,olleH".
Using `[::-1]` is a simple and concise way to reverse a string in Python, if you want to know how to reverse a number in python go here: https://coderhax.com/snippets/python/reverse-a-number
You can try the compile this python code here: https://pythondex.com/online-python-compiler
0
Maybe because the founders of Python did not find any better usage for negative integers of the third slice. Anyways I don't like it causes slice 1 and slice 2 to change places.
0
Thanks for all the answers!!!