How to reverse a string in Python

爱喝马黛茶的安东尼
Release: 2019-07-25 16:42:38
Original
29148 people have browsed it

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])
Copy after login

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))
Copy after login

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))
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!