Home > Article > Backend Development > How to reverse a string in Python
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)".
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"
>>> s="abcdef" >>> result = s[::-1] >>> print(result)
Output:
fedcba
l = list(s) l.reverse() result = "".join(l)
Of course the following will also work
l = list(s) result = "".join(l[::-1])
result = reduce(lambda x,y:y+x,s)
def func(s): if len(s) 4e1fae1cf39b83471a52b1b676fd13c60: result += l.pop() #模拟出栈 return result result = func(s)
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!