Skip to content

Instantly share code, notes, and snippets.

@artturijalli
Last active November 8, 2022 15:16
Embed
What would you like to do?
5 different ways to reverse a string in Python
# 1. Slicing
def reverse_slicing(s):
return s[::-1]
# 2. Looping with for and while loops
# 2.1 for loop
def reverse_for_loop(s):
s1 = ""
for c in s:
s1 = c + s1
return s1
# 2.2 while loop
def reverse_while_loop(s):
s1 = ""
l = len(s) - 1
while l >= 0:
s1 += s[l]
l -= 1
return s1
# 3. str.join() Method
def reverse_with_join(s):
return "".join(reversed(s))
# 4. list.reverse() Method
def reverse_with_list(s):
s_as_list = list(s)
s_as_list.reverse()
return "".join(s_as_list)
# 5. Recursion
def reverse_recursively(s):
if len(s) == 0:
return s
else:
return reverse_recursively(s[1:]) + s[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment