当前位置:网站首页>字符串反转的实现方法总结「建议收藏」
字符串反转的实现方法总结「建议收藏」
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
边栏推荐
- tooltips使用教程(鼠标悬停时显示提示)
- Kubernetes common commands
- Matlab矩阵基本操作(定义,运算)
- TRACE32——C源码关联
- R language moves time series data forward or backward (custom lag or lead period): use the lag function in the dplyr package to move the time series data forward by one day (set the parameter n to a p
- Gorm—Go语言数据库框架
- R language ggplot2 visualization: use the ggmapplot function of the ggpubr package to visualize the MA plot (MA-plot), the font.legend parameter and the font.main parameter to set the title and legend
- mysql black window ~ build database and build table
- Synchronized and volatile interview brief summary
- 6-22 Vulnerability exploit - postgresql database password cracking
猜你喜欢

Internet banking stolen?This article tells you how to use online banking safely

TextBlock控件入门基础工具使用用法,取上法入门

对话庄表伟:开源第一课

工程流体力学复习

浏览器自带的拾色器

After Grafana is installed, the web opens and reports an error

全新宝马3系上市,安全、舒适一个不落

What is the difference between BI software in the domestic market?

TRACE32 - SNOOPer-based variable logging

mongo enters error
随机推荐
Kubernetes原理剖析与实战应用手册,太全了
多主复制下处理写冲突(4)-多主复制拓扑
Dialogue with Zhuang Biaowei: The first lesson of open source
mysql黑窗口~建库建表
数据库的范式(第一范式,第二范式,第三范式,BCNF范式)「建议收藏」
Applicable Scenarios of Multi-Master Replication (1) - Multi-IDC
Implementing click on the 3D model in RenderTexture in Unity
TRACE32 - C source code association
Replication Latency Case (1) - Eventual Consistency
mysql black window ~ build database and build table
腾讯云部署----DevOps
数据表插入数据insert into
【MySQL】Mysql范式及外键作用
leetcode303 Weekly Match Replay
org.apache.jasperException(could not initialize class org)
R language ggplot2 visualization: use the ggboxplot function of the ggpubr package to visualize the grouped box plot, use the ggpar function to change the graphical parameters (caption, add, modify th
WPF项目--控件入门基础用法,必知必会XAML
mongo enters error
为什么黑客领域几乎一片男生?
TRACE32——常用操作