I'm learning how to reverse list and strings. Is there another way of reversing a string other than using [::-1] method? even if the other method is the long route i would much appreciate it
txt = ["Hello World"] st ="".join(txt) print(st[::-1])
Using string slicing as you have done is pretty much the best way, as discussed in this answer.
You should consistently put a space before and after the =
assignment operator, as recommended by PEP 8, the official Python style guide:
- Always surround these binary operators with a single space on either side: assignment (
=
), augmented assignment (+=
,-=
etc.), comparisons (==
,<
,>
,!=
,<>
,<=
,>=
,in
,not in
,is
,is not
), Booleans (and
,or
,not
).
Is there another way of reversing a string other than using [::-1] method?
Yes there is. There are plenty of tutorials on the Internet, consider this one for example: Python Reverse String - 5 Ways and the Best One. What's interesting is the performance comparison between the different options. Achieving best performance will usually be your goal, unless that makes the code too obscure or inflexible.
The [::-1]
is recommended because it is fast, short and to the point (and Pythonic). I don't have a better suggestion for you.
But to address your code specifically, it can be simplified since Python strings, like lists or tuples, are sequences. So for your purpose the string can be handled like a list:
txt = "Hello World" print(txt[::-1])
If you don't like the notation because you find it unusual, just write a function.
print("".join(reversed(txt)))
?)\$\endgroup\$list
to go on and''.join()
it is pointless:print("Hello World"[::-1])
.)\$\endgroup\$