3 ms·
From the article: String reverse Python doesn’t have a built-in reverse method for strings. Luckily, this can be easily done with slices: def reverse(str):
by BrandonM 18y ago
From the article:
String reverse
Python doesn’t have a built-in reverse method for strings. Luckily, this can be easily done with slices:
def reverse(str):
return str[::-1]
If you don't like str[::-1] (even though it is a common idiom), you could just use
"".join(reversed(str))
Is reversing a string really common enough to have a special function for it with such a general name like reverse?
- schtog 18y agoThere is a list-reverse that changes the list and returns None but maybe the reason there isn't one for strings are because they are immutable while lists are mutable.
- BrandonM 18y agoThat's a good point. I was thinking more along the lines, though, that there are some times where you actually need to reverse a list. How often does it make sense to reverse a string? When palindrome testing?