Home  >  Article  >  Backend Development  >  How to reverse a string in Python

How to reverse a string in Python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-22 15:59:3628977browse

How to reverse a string in Python

How to reverse a string in Python? Here are three methods to introduce to you:

Method 1

Using the fragmented screenshot function of string

str_2 = '我的世界因为有你才会美'
#字符串分片截图功能,从尾到头截图,步长为-1即倒序截取
print(str_2[::-1])

Method 2

Use the reverse() function of the list

Related recommendations: "Python Video Tutorial"

str_1 = 'abccdef'
#将字符串转换为list列表
lst = list(str_1)
#对列表进行反转操作,reverse()返回为None
lst.reverse()
print(''.join(lst))

Method 3

Using string traversal in reverse order

str_3 = '如果人人都献出一点爱,世界将变成美好的人间'
i = len(str_3) - 1
str_list = []
while(i >= 0):    
    str_list.append(str_3[i])    
    i = i - 1
print(''.join(str_list))

The above is the detailed content of How to reverse a string in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn