In this post, We will see different ways to Reverse a string in Python.
Code 1: Using the concept of string-Slicing.
# code1
# input
string = "Biochemithon"
# reverse a string using
# string slicing concept
reverse_string = string[ : : -1]
# show the output
print("Reverse String:",
reverse_string)
Output:
Reverse String: nohtimehcoiB
Code 2: Using the concept of Looping and string-Concatenation.
#code2
# input
string = "Biochemithon"
# empty string
rev_str = ""
# loop through each
# characters of the string
for i in string:
# string concatenation
rev_str = i + rev_str
# show the output
print("Reverse String:",
rev_str)
Output:
Reverse String: nohtimehcoiB
Code 3: Using the concept of Reverse Looping.
# code3
# input
input_str = "Biochemithon"
# empty string
rev_str = ""
# loop through each
# characters of the
# string from end
for i in range(len(input_str) - 1, -1, -1):
# string concatenation
rev_str += input_str[i]
# show the output
print("Reverse String:",
rev_str)
Output:
Reverse String: nohtimehcoiB
Code 4: Using reversed(),list() and join() function together.
# code4
# input
string = "Biochemithon"
# string reversal using
# reversed(),list() and
# join() function of python3
rev_str = "".join(list(reversed(string)))
# show the output
print("Reverse String:",
rev_str)
Output:
Reverse String: nohtimehcoiB
Code 5: Using the join() function and list-comprehension concept together.
# code5
# input
string = "Biochemithon"
# string reversal using
# list-comprehension and
# join() function of python3
reverse_str = "".join([string[i] for i in range(len(string)-1,
-1, -1)])
# show the output
print("Reverse String:",
reverse_str)
Output:
Reverse String: nohtimehcoiB
Code 6: Using the list of characters and join() function.
#code6
# input
string = "Biochemithon"
# convert the string into
# a list of characters
char_list = list(string)
# list reversal
char_list.reverse()
# form a string from a
# list of characters
reverse_string = "".join(char_list)
# show the output
print("Reverse String:",
reverse_string)
Output:
Reverse String: nohtimehcoiB