逆转字符串—输入一个字符串,将其逆转并输出。

实现Python字符串反转有4种方法:

1、列表的方式:

def rev(s):
    a = list(s)
    a.reverse()
    return (''.join(a))
a = rev('huowuzhao')
print (a)

---------------------------------------------------------------------------------
C:UsersAdministratorAppDataLocalProgramsPythonPython35python.exe D:/pycharm/hello.py
oahzuwouh
Process finished with exit code 0

这种方法是采用列表的reverse方法,先将s转换为列表,然后通过reverse方法反转,然后在通过join连接为字符串。

reverse是把列表方向排序;

2、切片的方式:

*切片的方式最简洁

def rev(s):
    return (s[::-1])
a = rev('huowuzhao')
print (a)

---------------------------------------------------------------------------

C:UsersAdministratorAppDataLocalProgramsPythonPython35python.exe D:/pycharm/hello.py
oahzuwouh

这是采用切片的方法,设置步长为-1,也就是反过来排序。
这种方法是最简洁的,也是最推荐的。

3、reduce:

from functools import reduce  #因为我是用的是Python3.5,所以reduce函数需要引入
def rev(s):
    return reduce(lambda x, y : y + x, s)
a = rev('huowuzhao')
print (a)

-----------------------------------------------------------------------------------------

C:UsersAdministratorAppDataLocalProgramsPythonPython35python.exe D:/pycharm/hello.py
oahzuwouh

4、还有一种类似切片的方法,不过稍微较前几种稍微复杂点:

def rev(s):
    str0 = ''
    l = len(s)-1
    while l >= 0:
       str0 += s[l]
       l -= 1
    return (str0)
a = rev('huowuzhao')
print (a)

---------------------------------------------------------------------------------

C:UsersAdministratorAppDataLocalProgramsPythonPython35python.exe D:/pycharm/hello.py
oahzuwouh

这种方法是先设置一个str0的空变量,然后在s中从后往前取值,然后追加到str0中。

 

原文地址:https://www.cnblogs.com/pythonal/p/5940982.html