Python – Different ways to Reverse a String

Python – Different ways to Reverse a String

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

Leave a Reply

Your email address will not be published.

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds