【python】字符串翻转
python中常见的字符串反转的方法
s = "abcdef"
#1. 切片操作
def string_reverse1(string):
print(string[::-1])
s1 = string_reverse1(s)
#2. 使用列表的reverse函数
def string_reverse2(string):
li = list(string)
li.reverse()
print(''.join(li))
s2 = string_reverse2(s)
#3. 采用递归的方式
def string_reverse3(string):
if string == "":
return s1
else:
return string_reverse3(string[1:])+string[0]
s3 = string_reverse(s)
print(s3)
#4. reduce函数
from functools import reduce
def string_reverse4(s):
return reduce(lambda x, y:y+x, s)
s4 = string_reverse(s)
print(s4)
#5. 空字符串翻转
def string_reverse5(string):
s = ''.join(reversed(string))
print(s)
s5 = string_reverse5(s)
#6. 交换位置
def string_reverse6(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)
s6 = string_reverse6(s)
print(s6)
#7. for循环
def string_reverse7(string):
return ''.join(string[i] for i in range(len(string)-1, -1, -1))
def string_reverse7(string):
a = ""
for i in range(len(string)-1, -1, -1):
a += string[i]
return a
s7 = string_reverse7(s)
print(s7)
还没有评论,来说两句吧...