当前位置:网站首页>字符串反转的实现方法总结「建议收藏」
字符串反转的实现方法总结「建议收藏」
2022-07-31 15:38:00 【全栈程序员站长】
大家好,又见面了,我是你们的朋友全栈君。
文章目录
方法1:对称交换法
str = 'abcdef'
def f(s):
s = list(s)
if len(s) <=1:
return s
i = 0
length = len(s)
while i < length/2:
s[i],s[length - 1 - i] = s[length - 1 - i],s[i]
i += 1
return ''.join(s)
newStr = f(str)
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 遍历字符串前一半的元素,然后与后一半对称的那个位置的元素进行交换,以达到字符串反转。
方法2:函数递归法
str = 'abcdef'
print(str[:-1]) # str[:-1] 截取除最后一个元素外的所有元素(-1 表示最后一个元素的索引)
def fun(s):
if len(s) <= 1:
return s
return s[-1] + fun(s[:-1])
newStr = fun(str)
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 使用递归的思想,建立函数,倒序添加字符串,直到字符串长度小于等于1后停止。
方法3:列表反转法
str = 'abcdef'
ll = list(str) # list()方法将字符串转换成了列表 ['a', 'b', 'c', 'd', 'e', 'f']
ll.reverse() # 将list反转,变成了 ['f', 'e', 'd', 'c', 'b', 'a']
newStr = ''.join(ll) # 采用join()方法遍历列表,合并成一个字符串
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: Python中,列表可以进行反转,我们只要把字符串转换成列表,使用reverse()方法,进行反转,然后再使用字符串的join()方法遍历列表,合并成一个字符串。
方法4:循环反向迭代法
str1 = 'abcdef'
str2 = ''
for i in str1:
str2 = i + str2
print('反转前的字符串:', str1) # abcdef
print('反转后的字符串:', str2) # fedcba说明: 字符串属于序列的一种,我们可以使用for循环遍历字符串,然后,不断反向赋值给变量str2,最后输出变量str2,就完成了字符串反转。
方法5:倒序切片法
str = 'abcdef'
newStr = str[::-1]
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 利用切片特性,一步到位
方法6:遍历索引法
str = 'abcdef'
newStr = ''
for i in range(1, len(str)+1):
newStr = newStr + str[-i]
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: *字符串作为序列,可以进行索引处理,所以我们先遍历索引数字,然后倒序提取字母,然后合并成字符串。
方法7:反向遍历索引法
str = 'abcdef'
newStr = ''
print(len(str)) # 6
for i in range(len(str)-1, -1, -1):
newStr = newStr + str[i]
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明:range()函数有三个参数:start,end,step,且左闭右开,我们从最后一个索引开始,最开始的索引结束,倒序遍历索引,然后反向提取字符串,最后合并
方法8:列表弹出法
str = 'abcdef'
str = list(str) # 将字符串str转换成列表 ['a', 'b', 'c', 'd', 'e', 'f']
newStr = ''
while len(str) > 0:
newStr = newStr + str.pop()
print('反转后的字符串:', newStr) # fedcba说明: 列表有一种弹出的方法pop(),默认弹出的是最后一个元素。每弹出一个元素就加入到空字符串 newStr中,最终实现原字符串的反转。
方法9:反向循环迭代法
str = 'abcdef'
newStr = ''
for i in str[::-1]:
newStr = newStr + i
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba代码改进:
str = 'abcdef'
newStr = ''.join(i for i in str[::-1])
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 使用列表解析式,然后通过join()方法,反转合并字符串。
方法10:累积相加法
str = 'abcdef'
from functools import reduce
def f(x,y):
return y + x
newStr = reduce(f,str)
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 使用python中的reduce()函数。先创建一个字符串倒序相加函数,然后将字符串和新创建的函数一起传入reduce()函数中,进行字符串倒序累积相加,最后实现反转字符串。
方法11:匿名函数法
str = 'abcdef'
from functools import reduce
newStr = reduce(lambda x,y:y+x,str)
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明:方法10的进阶版,使用lambda匿名函数创建字符串倒序相加函数,然后进行累积相加,得到字符串反转结果。
方法12:列表倒序法
str = 'abcdef'
ll = list(str) # 将字符串str转换成列表 ['a', 'b', 'c', 'd', 'e', 'f']
ll.sort(reverse=True) # 列表降序排列
newStr = ''.join(ll)
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 采用列表的sort(reverse=True)方法,降序排列,不过,这一方法有个弊端,它并不是按字符串的顺序进行升序或降序排列,而是按 “ASCII 字符顺序” 进行排序,所以,如果字符串不是按从小到大排列,那么运行后,排序会是错误的。
方法13:双向队列排序法
str = 'abcdef'
import collections
newStr = collections.deque()
for i in str:
newStr.appendleft(i)
newStr = ''.join(newStr)
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 遍历字符串,向左添加入双向队列中,最后使用join()方法合并,实现字符串反转。
方法14:双向队列反转法
str = 'abcdef'
import collections
newStr = collections.deque()
newStr.extend(list(str))
newStr.reverse()
newStr = ''.join(newStr)
print('反转前的字符串:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 同样使用双向队列,把字符串转换成列表添加到队列中,然后整个进行反转,使用join()方法合并,实现字符串反转。
文章参考:小詹学Python 公众号的 《面试官让用 5 种 python 方法实现字符串反转 ?对不起我有16种……》
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/127982.html原文链接:https://javaforall.cn
边栏推荐
猜你喜欢

AVH Deployment Practice (1) | Deploying the Flying Paddle Model on Arm Virtual Hardware

Kubernetes common commands

mongo进入报错

Ubantu project 4: xshell, XFTP connected the virtual machine and set xshell copy and paste the shortcut

【CUDA学习笔记】初识CUDA

苹果官网样式调整 结账时产品图片“巨大化”

【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发

mysql黑窗口~建库建表

Synchronized and volatile interview brief summary

How useful is four-quadrant time management?
随机推荐
TRACE32——C源码关联
贪吃蛇项目(简单)
复制延迟案例(3)-单调读
RecyclerView高效使用第二节
The new BMW 3 Series is on the market, with safety and comfort
基于ABP实现DDD
What is the difference between BI software in the domestic market?
Excel quickly aligns the middle name of the table (two-word name and three-word name alignment)
R language ggplot2 visualization: use the ggboxplot function of the ggpubr package to visualize the box plot, use the font function to customize the font size, color, style (bold, italic) of the legen
OPPO在FaaS领域的探索与思考
在资源管理类中提供对原始资源的访问——条款15
苹果官网样式调整 结账时产品图片“巨大化”
WPF项目--控件入门基础用法,必知必会XAML
工程水文学试卷
border控件的使用
AVH Deployment Practice (1) | Deploying the Flying Paddle Model on Arm Virtual Hardware
Qt实战案例(54)——利用QPixmap设计图片透明度
radiobutton的使用
四象限时间管理有多好用?
RecyclerView的高效使用第一节