What is the method in Python to reverse a string?

There are multiple ways to reverse a string in Python, one of which is by using slice operation.

string = "hello"
reversed_string = string[::-1]
print(reversed_string)

Another approach is to use the reversed() function and the join() method.

string = "hello"
reversed_string = "".join(reversed(string))
print(reversed_string)

Another option is to use a loop to reverse the string:

string = "hello"
reversed_string = ""
for char in string:
    reversed_string = char + reversed_string
print(reversed_string)

Here are several common methods you can choose from to achieve string reversal.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds