当前位置:网站首页>字符串反转的实现方法总结「建议收藏」
字符串反转的实现方法总结「建议收藏」
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
边栏推荐
- "Autumn Recruitment Series" MySQL Interview Core 25 Questions (with answers)
- OPPO在FaaS领域的探索与思考
- [CUDA study notes] First acquaintance with CUDA
- 实现防抖与节流函数
- Why is the field of hacking almost filled with boys?
- Dialogue with Zhuang Biaowei: The first lesson of open source
- button控件的使用
- Synchronized and volatile interview brief summary
- .NET 20周年专访 - 张善友:.NET 技术是如何赋能并改变世界的
- Synchronized和volatile 面试简单汇总
猜你喜欢
随机推荐
button控件的使用
DBeaver连接MySQL 8.x时Public Key Retrieval is not allowed 错误解决
定时器的类型
多主复制的适用场景(2)-需离线操作的客户端和协作编辑
Efficient use of RecyclerView Section 2
Why is the field of hacking almost filled with boys?
Browser's built-in color picker
对话庄表伟:开源第一课
ML.NET相关资源整理
ASP.NET Core generates continuous Guid
Oracle dynamically registers non-1521 ports
Internet banking stolen?This article tells you how to use online banking safely
Public Key Retrieval is not allowed error solution when DBeaver connects to MySQL 8.x
"Autumn Recruitment Series" MySQL Interview Core 25 Questions (with answers)
Insert into data table to insert data
Getting Started with TextBlock Control Basic Tools Usage, Get Started
ansible study notes 02
AVH Deployment Practice (1) | Deploying the Flying Paddle Model on Arm Virtual Hardware
多主复制下处理写冲突(4)-多主复制拓扑
The use of button controls