+ 3

Is there any function like reverse() in python to reverse a given string??

20th May 2021, 4:28 PM
Anikur Rahman
Anikur Rahman - avatar
7 Answers
+ 8
use slicing: reversed = my_string[::-1]
20th May 2021, 4:30 PM
visph
visph - avatar
+ 7
Jan Markus , i was not aware of the *unpack operator together with reversed(), thanks!
21st May 2021, 5:23 PM
Lothar
Lothar - avatar
+ 6
Jan Markus , revesed() is working for strings. it looks not as elegant as the slice, but just for information: txt = "This is Major Tom to Ground Control, i'm stepping through the door" print("".join(reversed(txt)))
20th May 2021, 6:04 PM
Lothar
Lothar - avatar
+ 6
[::-1] is faster than reversed()
20th May 2021, 8:39 PM
David Ashton
David Ashton - avatar
+ 3
visph David Ashton Lothar Jan Markus Thanks a lot my dear friends
21st May 2021, 1:47 AM
Anikur Rahman
Anikur Rahman - avatar
+ 3
Jaweed it works as you said, but there's no need to put -1 at first slice argument ^^ (see the first post of this thread)
22nd May 2021, 4:32 PM
visph
visph - avatar
+ 2
Python String Slice s="Monty Python" print(s[-1: :-1]) # reversed all string
22nd May 2021, 4:25 PM
Jaweed
Jaweed - avatar