反轉字串的所有方法-Python實現
阿新 • • 發佈:2019-01-04
本文章轉自: http://blog.csdn.NET/caroline_wendy/article/details/23438739
大神總結的很好,分享給大家。
Python實現字串反轉一共包含5種方法, 其中第一種最簡單, 即步長為-1, 輸出字串,這個也叫作“分片法”;
方法如下
5種方法的比較:
1. 簡單的步長為-1, 即字串的翻轉(常用);
2. 交換前後字母的位置;
3. 遞迴的方式, 每次輸出一個字元;
4. 雙端佇列, 使用extendleft()函式;
5. 使用for迴圈, 從左至右輸出;
程式碼:
- # -*- coding: utf-8 -*-
- #eclipse pydev, python 3.3
- #by C.L.Wang
- #time: 2014. 4. 11
- string = 'abcdef'
- def string_reverse1(string):
- return string[::-1]
- def string_reverse2(string):
- t = list(string)
- l = len(t)
- for i,j in zip(range(l-1, 0, -1), range(l//2)):
- t[i], t[j] = t[j], t[i]
- return "".join(t)
- def string_reverse3(string):
- if len(string) <= 1:
- return string
- return string_reverse3(string[1:]) + string[0]
- from collections import deque
- def string_reverse4(string):
- d = deque()
- d.extendleft(string)
- return ''.join(d)
- def string_reverse5(string):
- #return ''.join(string[len(string) - i] for i in range(1, len(string)+1))
- return ''.join(string[i] for i in range(len(string)-1, -1, -1))
- print(string_reverse1(string))
- print(string_reverse2(string))
- print(string_reverse3(string))
- print(string_reverse4(string))
- print(string_reverse5(string))
# -*- coding: utf-8 -*-
#eclipse pydev, python 3.3
#by C.L.Wang
#time: 2014. 4. 11
string = 'abcdef'
def string_reverse1(string):
return string[::-1]
def string_reverse2(string):
t = list(string)
l = len(t)
for i,j in zip(range(l-1, 0, -1), range(l//2)):
t[i], t[j] = t[j], t[i]
return "".join(t)
def string_reverse3(string):
if len(string) <= 1:
return string
return string_reverse3(string[1:]) + string[0]
from collections import deque
def string_reverse4(string):
d = deque()
d.extendleft(string)
return ''.join(d)
def string_reverse5(string):
#return ''.join(string[len(string) - i] for i in range(1, len(string)+1))
return ''.join(string[i] for i in range(len(string)-1, -1, -1))
print(string_reverse1(string))
print(string_reverse2(string))
print(string_reverse3(string))
print(string_reverse4(string))
print(string_reverse5(string))
輸出:
- fedcba
- fedcba
- fedcba
- fedcba
- fedcba