字符串反转

上一篇 / 下一篇  2017-06-28 11:15:46 / 个人分类:Python实例

def reverse_fun(s):
    print(id(s))
    m = list(s)
    n = []
    for i in range(0,len(m)):
        n.append(m.pop())
    return "".join(n)

def reverse_fun_method2(s):
    r = ''
    for i in range(len(s)-1,-1,-1):
        r += s[i]
    return r

s = 'Hello World'
print(id(s))
print('method one result %s'%reverse_fun(s))
print('method two result %s'%reverse_fun_method2(s))

输出结果:
49173248
49173248
method one result dlroW olleH
method two result dlroW olleH


要点:字符串与列表的相互转化
>>> s = "xxxxx"
>>> list(s)
['x', 'x', 'x', 'x', 'x']
>>> tuple(s)
('x', 'x', 'x', 'x', 'x')
>>> tuple(list(s))
('x', 'x', 'x', 'x', 'x')
>>> list(tuple(s))
['x', 'x', 'x', 'x', 'x']

>>> "".join(tuple(s))
'xxxxx'
>>> "".join(list(s))
'xxxxx'
>>> str(tuple(s))
"('x', 'x', 'x', 'x', 'x')"
>>> 

TAG:

 

评分:0

我来说两句

Open Toolbar