Home > Article > Backend Development > 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!