+ 2
Don't understand python reverse construction.
Hello to revers string you need this code(find in internet) s = input() rev = s [::-1] print(rev) I didn't understand 2 line. What's going on ?
3 Respostas
+ 9
You have already completed the Intro to Python course. I suggest to review the chapter about list slices.
s is a string, and a string can be sliced just like a normal list. Each element of a string is a character.
The general format of a slice is
[start:end]
or
[start:end:step]
start is the index of the first element included in the slice, end is the last index that is no longer included.
step is optional, by default 1.
When step is negative, the direction goes from the highest to the lowest index, so this is practically reverse direction.
When start or end are not specified, then there is no restriction about the beginning or ending position.
+ 2
The second line of code, `rev = s[::-1]`, is using Python's slice notation to reverse the string `s`. Let me break it down for you:
- `s`: This is your original string.
- `[::-1]`: This is the slice notation. It's a way of creating a subsequence of a sequence (like a string or a list). When used with `[::-1]`, it means to create a new sequence that starts from the end and goes backward with a step size of -1.
So, `s[::-1]` essentially means "take the whole string `s` and create a new string that consists of all the elements, but in reverse order."
Here's an example to illustrate:
```python
s = "hello"
rev = s[::-1]
print(rev)
```
Output:
```
olleh
```
In this example, `s[::-1]` creates a new string that is the reverse of the original string "hello". The resulting string is assigned to the variable `rev`, which is then printed.
+ 1
I like this question and the answer.
This kind of question appears in code challenge too.
However, this syntax is not explained in current available python courses.
It is possible someone wrote comments during the courses but I didn't check.
Maybe we should send feedback to SoloLearn and ask them to include it in the course.