Write a program to reverse a string in Python
What is string reversal in Python ? How to use the string reverse function in Python ? Let's find out with TipsMake!
Programming is currently one of the hottest professions today. This is because technology is an inevitable trend of the times. The more technology develops, the more comfortable and easier human life becomes. Programming is the core of technology. Lines of code that seem meaningless and difficult to understand can, in fact, create a whole program or software that is useful for life.
Currently, you have many different programming language options. Python is a prominent and popular choice among them. It's not difficult to learn programming in Python. You can take a formal course or study on your own at home. If you don't know where to start, please refer to the basic Python learning section on TipsMake.
In this article, let's learn about Python reverse strings, write string reverse functions in Python, and other related information.
If you've been programming for a while, you've probably faced a situation where you needed to reverse a string. In fact, this is a common problem when developing web/app or learning to code. You can reverse a string using built-in functions or write your own code to implement the reverse function.
Python has many useful string functions, such as casefold() which converts a string to lower case. There is no string reverse function in this language. However, you have many simple methods to reverse strings in Python.
The method you choose depends on personal preference. The article below will summarize for you the simplest ways to reverse strings in Python.
Topic: Given a character string, write a program to print that character string in reversed order.
For example:
Input: TipsMake.com Output: gnamirtnauQ
1. Reverse a string in Python using a loop
In this example, we call a function to reverse a string, which iterates over every element and intelligently concatenates each character at the beginning to obtain the reversed string.
Sample code:
def reverse(s): str = "" for i in s: str = i + str return str s = "TipsMake" print("Chuỗi ban đầu là : ", end="") print(s) print("Chuỗi đã được đảo ngược (sử dụng vòng lặp) là : ", end="") print(reverse(s))
2. Reverse a string in Python using recursion
The string is passed as an argument to a recursive function to reverse the string. In the function, the basic condition is that if the length of the string is 0 then the string is returned. If not equal to 0, the reverse function is called recursively to cut the part of the string except the first character and concatenate the first character with the remaining part of the string.
Sample code:
def reverse(s): if len(s) == 0: return s else: return reverse(s[1:]) + s[0] s = "TipsMake" print("Chuỗi ban đầu là : ", end="") print(s) print("Chuỗi đã được đảo ngược (sử dụng đệ quy) là: ", end="") print(reverse(s))
3. Reverse a string in Python using a stack
An empty stack is created. One by one, the string's characters are pushed onto the stack. One by one all the characters in the stack are output and returned to the string.
Sample code:
# Function to create an empty stack. It # initializes size of stack as 0 def createStack(): stack = [] return stack # Function to determine the size of the stack def size(stack): return len(stack) # Stack is empty if the size is 0 def isEmpty(stack): if size(stack) == 0: return true # Function to add an item to stack . It # increases size by 1 def push(stack, item): stack.append(item) # Function to remove an item from stack. # It decreases size by 1 def pop(stack): if isEmpty(stack): return return stack.pop() # A stack based function to reverse a string def reverse(string): n = len(string) # Create a empty stack stack = createStack() # Push all characters of string to stack for i in range(0, n, 1): push(stack, string[i]) # Making the string empty since all # characters are saved in stack string = "" # Pop all characters of string and put # them back to string for i in range(0, n, 1): string += pop(stack) return string # Driver code s = "TipsMake" print("Chuỗi ban đầu là : ", end="") print(s) print("Chuỗi sau khi đảo ngược (sử dụng ngăn xếp) là: ", end="") print(reverse(s))
4. Reverse a string in Python using slice extended
Slice extended suggests setting the "step" field to [start, stop, step] and leaving no fields as start and stop indicating default values of 0 and string length respectively, and "-1" indicating start from the end and stop at the start, thus reversing a string.
Sample code:
# Function to reverse a string def reverse(string): string = string[::-1] return string s = "TipsMake" print("Chuỗi ban đầu là : ", end="") print(s) print("Chuỗi sau khi được đảo ngược (sử dụng slice extended) là: ", end="") print(reverse(s))
5. Reverse a string in Python using the reversed() method
The reversed() method returns the reversed iterator of the given string and then the elements of the string are joined with the separated empty string using join(). And the reverse sequence is formed.
Sample code:
# Python code to reverse a string # using reversed() # Function to reverse a string def reverse(string): string = "".join(reversed(string)) return string s = "TipsMake" print("Chuỗi ban đầu là: ", end="") print(s) print("Chuỗi sau khi đảo ngược (sử dụng reversed) là: ", end="") print(reverse(s))
The slice method is faster mainly because the join() function creates a new list. However, using the join() function is easier to read. It is the method most worth trying if the program does not have comments.
6. Reverse a string in Python using list comprehension()
List comprehension creates a list of elements of a string in reverse order and then its elements are concatenated using join(). And the chain in reverse order is formed.
Sample code:
# Function to reverse a string def reverse(string): string = [string[i] for i in range(len(string)-1, -1, -1)] return "".join(string) s = "TipsMake" print("Chuỗi ban đầu là: ", s) print("Chuỗi sau khi đảo ngược (sử dụng list comprehension) là : ", reverse(s))
7. Reverse a string in Python using a function call
The function will reverse a string by converting it to a list then reversing it and converting it back to a string.
Sample code:
# Function to reverse a string # by converting string to list # then reversed it and again convert it to string def reverse(string): string = list(string) string.reverse() return "".join(string) s = "TipsMake" print("Chuỗi ban đầu là: ", s) print("Chuỗi đã được đảo ngược (sử dụng lệnh gọi hàm) là: ", reverse(s)) # This code is contributed by Susobhan AKhuli
Performance comparison of Python reversed strings
Below is an effective comparison between string reversal methods in Python.
- To repeat performance tests on the system:
- Create a Python file named reverse_strings.py .
- Copy & paste all string reversal methods into the file.
- Open a command line or terminal window .
- Run the terminal commands below to see execution time.
$ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_slicing("This is just a tests")' 100000 loops, best of 5: 0.377 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_for_loop("This is just a tests")' 100000 loops, best of 5: 1.84 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_while_loop("This is just a tests")' 100000 loops, best of 5: 2.94 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_with_join("This is just a tests")' 100000 loops, best of 5: 1.01 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_with_list("This is just a tests")' 100000 loops, best of 5: 0.87 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_recursively("This is just a tests")' 100000 loops, best of 5: 6.29 usec per loop
As you can see, the slice approach is the fastest.
Hope this article will be useful to you!
You should read it
- Write a program to check duplicate values in Python
- Instructions for creating reverse text
- Python data type: string, number, list, tuple, set and dictionary
- For in Python loop
- Write a program to find the majority element in an array in Python
- Write an alarm clock program in Python
- Write a program to check password in Python
- The reversed () function in Python
- Write a program to print Pascal's Triangle in Python
- Write a program to calculate the square root of a number in Python
- Write a program to find duplicate values in Python
- Write a program to move zeros in Python
Maybe you are interested
Summary of functions that handle character strings in Excel, syntax and examples
The computer now finalizes the string, solving it in a flash
How to insert characters at the beginning or end of a string in Excel
How to separate text strings by commas or spaces in Excel
Instructions for cutting strings, concatenating strings in Excel
The function takes a string in Excel