Last active
November 8, 2022 15:16
-
-
Save artturijalli/3689ee33e52c26f6b198f334124c1147 to your computer and use it in GitHub Desktop.
5 different ways to reverse a string in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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