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

How to reverse a string in Python

silencement
silencementOriginal
2019-05-23 15:08:3818565browse

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)

Output:

fedcba

th Two: use the reverse method of the list

l = list(s)
l.reverse()
result = "".join(l)

Of course the following will also work

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

The third: use reduce

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

The fourth: use the recursive function

def func(s):
    if len(s) 4e1fae1cf39b83471a52b1b676fd13c60:
        result += l.pop() #模拟出栈
    return result
result = func(s)

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)

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
Previous article:Is python widely used?Next article:Is python widely used?