How to reverse a string in Python

silencement
Release: 2020-09-19 11:53:25
Original
18503 people have browsed it

Reversal method: 1. Use the slicing method to reverse, the syntax is "String[::-1]". 2. First convert the string into a list; then use reverse() to reverse the list elements; finally convert the reversed list into a string. 3. Use the reduce() function, the syntax is "reduce(lambda x,y:y x,string)".

How to reverse a string in Python

A very boring question encountered in the interview~~~

Requirement: Use as many methods as possible to reverse in the Python environment String, for example, reverse s = "abcdef" to "fedcba"

First method: use string slicing

>>> s="abcdef"
>>> result = s[::-1]
>>> print(result)
Copy after login

Output:

fedcba
Copy after login

th Two: use the reverse method of the list

l = list(s)
l.reverse()
result = "".join(l)
Copy after login

Of course the following will also work

l = list(s)
result = "".join(l[::-1])
Copy after login

The third: use reduce

result = reduce(lambda x,y:y+x,s)
Copy after login

The fourth: use the recursive function

def func(s):
    if len(s) <1:
        return s
    return func(s[1:])+s[0]
result = func(s)
Copy after login

The fifth way: using stack

def func(s):
    l = list(s) #模拟全部入栈
    result = ""
    while len(l)>0:
        result += l.pop() #模拟出栈
    return result
result = func(s)
Copy after login

The sixth way: for loop

def func(s):
    result = ""
    max_index = len(s)-1
    for index,value in enumerate(s):
        result += s[max_index-index]
    return result
result = func(s)
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!