实现字符串反转的几种方法总结:
1、linux/shell 命令行
echo '123' | rev
2、使用字符串的切片
num = '123'
num11 = num[::-1]
3、先转化为列表,使用列表的reverse方法
num1 = list(num)
num1.reverse() # num1列表倒置,num1变成倒置后的新列表,num1.reverse()不产生新值,赋值无效
res = "".join(num1)
4、利用列表的切片
num1 = list(num)
num2 = num1[::-1] #num2列表倒置,num1不变
res = ''.join(num2)
5、使用reduce
6、使用递归函数
s = '123'
def func(s):
l = list(s) #模拟全部入栈
result = ""
while len(l)>0:
result += l.pop() #模拟出栈
return result
result = func(s)
7、利用for循环
s = '123'
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)
8、使用栈
s = '123'
def func(s):
l = list(s) #模拟全部入栈
result = ""
while len(l)>0:
result += l.pop() #模拟出栈
return result
result = func(s)