Python中的字符串逆序处理
目录
在Python中,字符串是一个Unicode字符序列。Python没有内置(built-in)函数或者方法用于字符串逆序处理。有以下几种能够实现字符串的方法。
1. Decreasing slicing
Python中的string slicing的语法如下:
string[start:stop:step]
省略start和stop的设置,step置为’-1’的话就可以得到原字符串的一个逆序的副本。
2. Using reversed() function
内置的函数reversed()对字符串进行逆序处理,但是它不是直接返回原字符串的逆序副本,而是生成一个iterator。可以用”join()”操作符对这个iterator作进一步的处理以生成字符串逆序副本。
3. Using list reverse()
Python中的List有reverse() method,所以可以按以下步骤实现字符串逆序:
- 将字符串转换为字符列表
- 对字符列表进行逆序处理
- 将逆序字符列表再变换回字符串
4. Using recursion function
最后还有一种超级费力的方式,就是用递归函数调用的方式(只有秀编程技巧的价值)。定义一个函数,每次调用将首字符挪到字符串尾部,直到整个字符串顺序完全颠倒为止
参见以下代码示例:
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 19 13:19:27 2021
@author: chenxy
"""
import timeit
from statistics import mean
def rev_str_thru_slicing(aStr):
return aStr[::-1]
def rev_str_thru_join_revd(aStr):
return "".join(reversed(aStr))
def rev_str_thru_list_reverse(aStr):
lst = list(aStr)
lst.reverse()
return(''.join(lst))
def rev_str_thru_recursion(aStr):
if len(aStr) == 0:
return aStr
else:
return rev_str_thru_recursion(aStr[1:]) + aStr[0]
if __name__ == '__main__':
#1. Decreasing slicing
print('Decreasing slicing: ','HelloPython'[::-1])
#2. User-defined function based on decreasing slicing
myStr = "HelloPython"
print('User-defined function based on: ',rev_str_thru_slicing(myStr))
#3. Using reversed() function
print('Using reversed() function: ',rev_str_thru_join_revd(myStr))
#4. Using list reverse() method
print('Using list reverse() method: ',rev_str_thru_list_reverse(myStr))
#4. Using recursive function
print('Using recursive function: ',rev_str_thru_recursion(myStr))
5. 性能比较分析
最后,基于python的timeit模块对以上几种字符串逆序处理方法进行一个统计平均性能对比。Timeit的repeat选项用于对代码进行重复执行,然后可以对运行所耗费的时间进行统计平均以得到平均执行时间。Repeat的单位是1百万次,即repeat设为1时待评估的对象代码会被重复执行1百万次。
# Performance comparison
s = myStr * 10
repeatCount = 10
SLICING_PERF = timeit.repeat(lambda: rev_str_thru_slicing(s), repeat=repeatCount)
print(min(SLICING_PERF), mean(SLICING_PERF), max(SLICING_PERF), SLICING_PERF)
J_R_PERF = timeit.repeat(lambda: rev_str_thru_join_revd(s), repeat=repeatCount)
print(min(J_R_PERF), mean(J_R_PERF), max(J_R_PERF), J_R_PERF)
LIST_PERF = timeit.repeat(lambda: rev_str_thru_list_reverse(s), repeat=repeatCount)
print(min(LIST_PERF), mean(LIST_PERF), max(LIST_PERF), LIST_PERF)
RECUR_PERF = timeit.repeat(lambda: rev_str_thru_recursion(s), repeat=repeatCount)
print(min(RECUR_PERF), mean(RECUR_PERF), max(RECUR_PERF), RECUR_PERF)
ratio0 = mean(SLICING_PERF)/mean(SLICING_PERF)
ratio1 = mean(J_R_PERF)/mean(SLICING_PERF)
ratio2 = mean(LIST_PERF)/mean(SLICING_PERF)
ratio3 = mean(RECUR_PERF)/mean(SLICING_PERF)
print('SLICING_PERF:J_R_PERF:LIST_PERF:RECUR_PERF = {0}:{1}:{2}:{3}'.format(ratio0,ratio1,ratio2,ratio3))
运行结果:
SLICING_PERF:J_R_PERF:LIST_PERF:RECUR_PERF = 1.0:7.45:6.18:97.43
不出意外,用decreasing slicing的方式最快。而递归实现方式则满了接近两个数量级!
《Python学习点滴》系列其它小知识参见:
Python elapsed time evaluation: time module
Reference: https://linuxize.com/post/python-reverse-string/
相关文章
- Python学习--12 异常处理、调试
- 跨平台python异步回调机制实现和使用方法
- python处理文件、文件夹-小结
- Python 图像处理 OpenCV (6):图像的阈值处理
- Python 图像处理 OpenCV (3):图像属性、图像感兴趣 ROI 区域及通道处理
- 【Python五篇慢慢弹(4)】模块异常谈python
- Python 字符串_python 字符串截取_python 字符串替换_python 字符串连接
- Python 日期和时间_python 当前日期时间_python日期格式化
- python处理xml文件
- python: 安装DeOldify库:黑白图片上色(Python 3.7.15)
- Python 分割字符串时有多个分隔符怎么处理?
- Atitit 读取音频音乐文件的bpm 目录 1.1. Librosa是一个用于音频、音乐分析、处理的python工具包,1 1.2. bpm.py1 1.3. Echo2 1.4. Cod
- Python编程语言学习:python语言中快速查询python自带模块&函数的用法及其属性方法、如何查询某个函数&关键词的用法、输出一个类或者实例化对象的所有属性和方法名之详细攻略
- Python:利用python语言实现18位身份证号码和15位身份证号码相互转换
- Python语言学习之打印输出那些事:python输出图表和各种吊炸天的字符串或图画、版权声明(如README.md)等之详细攻略
- 已解决2. Set PROTOCOL_BUPFERS_PYTHON_iMPLEMENTATION=python (but this will use pure-Python parsing and w
- Python图像处理丨基于OpenCV和像素处理的图像灰度化处理
- python 字符串最常用的13个处理操作
- Python爬虫:滤网架构处理爬虫数据
- 【异常】前端ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
- 〖Python自动化办公篇⑲〗 - python实现邮件自动化 - 邮件发送
- opencv-python图片处理之哈哈镜
- python 自然语言处理(三)获取词性