![]() ![]() In this method, we use a for loop to iterate over the characters in the string and build a new string by adding each character to the beginning of an empty string. Read: Python string formatting Method-3: Python program to reverse a string using For loop The code then calls the reverse_string function with the argument “USA” and prints the returned value, which is the reverse of the string “USA”. The function uses the reversed function and the join method to reverse the string. The above code defines a function reverse_string which takes a string as an argument and returns the reversed version of the string. Print("Reverse of the string is : ", reverse_string("USA")) # Return the reversed string using the reversed() function and join() method This method is easy to use and more efficient than some other methods. The reversed() function returns a reverse iterator, so we can convert it into a string using the join() method. Read: How to Check if a String contains a Substring in Python Method-2: Python program to reverse a string using the reversed() function Python reverse string Using the slicing method The function is then called and the reverse of the string “United Kingdom” is printed to the console. The above code defines a function called reverse_string which takes a string as an argument and returns the reverse of the input string using string slicing. Print("Reverse of the string is : ", reverse_string("United Kingdom")) ![]() # Testing the function with the input string "United Kingdom" ![]() # Returns the reversed string by slicing from the end to the beginning This method uses the slicing of Python strings to reverse the string by starting from the last character and returning every character to the first one with a step of -1. Method-1: Python program to reverse a string using the slicing method And we will start with the first method of using slicing. Let us all 8 methods to reverse a string in Python using examples.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |