Python中字符串的处理技巧分享


Posted in Python onSeptember 17, 2016

一、如何拆分含有多种分隔符的字符串?

实际案例

我们要把某个字符串依据分隔符号拆分不同的字符段,该字符串包含多种不同的分隔符,例如:

s = 'asd;aad|dasd|dasd,sdasd|asd,,Adas|sdasd;Asdasd,d|asd'

其中<,>,<;>,<|>,<\t>都是分隔符,如何处理?

解决方案

连续使用split()方法,每次处理一种分隔符

# 使用Python2 def mySplit(s,ds): res = [s] for d in ds: t = [] map(lambda x: t.extend(x.split(d)), res) res = t return [x for x in res if x] s = 'asd;aad|dasd|dasd,sdasd|asd,,Adas|sdasd;Asdasd,d|asd' result = mySplit(s, ';,|\t') print(result)
C:\Users\Administrator>C:\Python\Python27\python.exe E:\python-intensive-training\s2.py ['asd', 'aad', 'dasd', 'dasd', 'sdasd', 'asd', 'Adas', 'sdasd', 'Asdasd', 'd', 'asd']

使用正则表达式的re.split()方法,一次性拆分字符串

>>> import re >>> re.split('[,;\t|]+','asd;aad|dasd|dasd,sdasd|asd,,Adas|sdasd;Asdasd,d|asd') ['asd', 'aad', 'dasd', 'dasd', 'sdasd', 'asd', 'Adas', 'sdasd', 'Asdasd', 'd', 'asd']

二、如何判断字符串a是否以字符串b开头或结尾?

实际案例

如某目录有如下文件:

quicksort.c graph.py heap.java install.sh stack.cpp ......

现在需要给.sh.py结尾的文件夹上可执行权限

解决方案

使用字符串的startswith()endswith()方法

>>> import os, stat >>> os.listdir('./') ['heap.java', 'quicksort.c', 'stack.cpp', 'install.sh', 'graph.py'] >>> [name for name in os.listdir('./') if name.endswith(('.sh','.py'))] ['install.sh', 'graph.py'] >>> os.chmod('install.sh', os.stat('install.sh').st_mode | stat.S_IXUSR)
[root@iZ28i253je0Z t]# ls -l install.sh -rwxr--r-- 1 root root 0 Sep 15 18:13 install.sh

三、如何调整字符串中文本的格式?

实际案例

某软件的日志文件,其中日期格式为yyy-mm-dd:

2016-09-15 18:27:26 statu unpacked python3-pip:all 2016-09-15 19:27:26 statu half-configured python3-pip:all 2016-09-15 20:27:26 statu installd python3-pip:all 2016-09-15 21:27:26 configure asdasdasdas:all python3-pip:all

需要把其中日期改为美国日期的格式mm/dd/yyy, 2016-09-15 --> 09/15/2016,要如何处理?

解决方案

使用正则表达式re.sub()方法做字符串替换

利用正则表达式的捕获组,捕获每个部分内容,在替换字符串中各个捕获组的顺序。

>>> log = '2016-09-15 18:27:26 statu unpacked python3-pip:all' >>> import re # 按顺序 >>> re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1' , log) '09/15/2016 18:27:26 statu unpacked python3-pip:all' # 使用正则表达式的分组 >>> re.sub('(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', r'\g<month>/\g<day>/\g<year>' , log) '09/15/2016 18:27:26 statu unpacked python3-pip:all'

四、如何将多个小字符串拼接成一个大的字符串?

实际案例

在设计某网络程序时,我们自定义了一个基于UDP的网络协议,按照固定次序向服务器传递一系列参数:

hwDetect: "<0112>" gxDepthBits: "<32>" gxResolution: "<1024x768>" gxRefresh: "<60>" fullAlpha: "<1>" lodDist: "<100.0>" DistCull: "<500.0>"

在程序中我们将各个参数按次序收集到列表中:

["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]

最终我们要把各个参数拼接成一个数据包进行发送:

"<0112><32><1024x768><60><1><100.0><500.0>"

解决方案

迭代列表,连续使用'+'操作依次拼接每一个字符串

>>> for n in ["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]: ... result += n ... >>> result '<0112><32><1024x768><60><1><100.0><500.0>'

使用str.join()方法,更加快速的拼接列表中所有字符串

>>> result = ''.join(["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]) >>> result '<0112><32><1024x768><60><1><100.0><500.0>'

如果列表中有数字,可以使用生成器进行转换:

>>> hello = [222,'sd',232,'2e',0.2] >>> ''.join(str(x) for x in hello) '222sd2322e0.2'

五、如何对字符串进行左, 右, 居中对齐?

实际案例

某个字典中存储了一系列属性值:

{ 'ip':'127.0.0.1', 'blog': 'www.anshengme.com', 'title': 'Hello world', 'port': '80' }

在程序中,我们想以以下格式将其内容输出,如何处理?

ip : 127.0.0.1 blog : www.anshengme.com title : Hello world port : 80

解决方案

使用字符串的str.ljust() , str.rjust,str.cente()进行左右居中对齐

>>> info = {'ip':'127.0.0.1','blog': 'www.anshengme.com','title': 'Hello world','port': '80'} # 获取字典中的keys最大长度 >>> max(map(len, info.keys())) 5 >>> w = max(map(len, info.keys())) >>> for k in info: ... print(k.ljust(w), ':',info[k]) ... # 获取到的结果 port : 80 blog : www.anshengme.com ip : 127.0.0.1 title : Hello world

使用format()方法,传递类似'<20','>20','^20'参数完成同样任务

>>> for k in info: ... print(format(k,'^'+str(w)), ':',info[k]) ... port : 80 blog : www.anshengme.com ip : 127.0.0.1 title : Hello world

六、如何去掉字符串中不需要的字符?

实际案例

过滤掉用户输入卡后多余的空白字符: anshengm.com@gmail.com

过滤某windows下编辑文本中的'\r': hello word\r\n

去掉文本中的unicode组合符号(音调): ‘ní hǎo, chī fàn'

解决方案

字符串strip() , lstrip(),rstrip()方法去掉字符串两端字符

>>> email = ' anshengm.com@gmail.com ' >>> email.strip() 'anshengm.com@gmail.com' >>> email.lstrip() 'anshengm.com@gmail.com ' >>> email.rstrip() ' anshengm.com@gmail.com' >>>

删除某个固定位置的字符,可以使用切片+拼接的方法

>>> s[:3] + s[4:] 'abc123'

字符串的replace()方法或正则表达式re.sub()删除任意位置字符

>>> s = '\tabc\t123\txyz' >>> s.replace('\t', '') 'abc123xyz'

使用re.sub()删除多个

>>> import re >>> re.sub('[\t\r]','', string) 'abc123xyzopq'

字符串translate()方法,可以同时删除多种不同字符

>>> import string >>> s = 'abc123xyz' >>> s.translate(string.maketrans('abcxyz','xyzabc')) 'xyz123abc'
>>> s = '\rasd\t23\bAds' >>> s.translate(None, '\r\t\b') 'asd23Ads'
# python2.7 >>> i = u'ní hǎo, chī fàn' >>> i u'ni\u0301 ha\u030co, chi\u0304 fa\u0300n' >>> i.translate(dict.fromkeys([0x0301, 0x030c, 0x0304, 0x0300])) u'ni hao, chi fan'

总结

以上就是为大家整理的Python中字符串的处理技巧,文中通过案例、解决方案以及实例来演示如何解决,对大家学习或者使用python具有一定的参考借鉴价值。有需要的可以参考借鉴。

Python 相关文章推荐
python多进程操作实例
Nov 21 Python
pyqt5 获取显示器的分辨率的方法
Jun 18 Python
Python 正则表达式爬虫使用案例解析
Sep 23 Python
python文件读写代码实例
Oct 21 Python
python通过链接抓取网站详解
Nov 20 Python
python 实现矩阵按对角线打印
Nov 29 Python
在pytorch中对非叶节点的变量计算梯度实例
Jan 10 Python
使用python-Jenkins批量创建及修改jobs操作
May 12 Python
python pyecharts 实现一个文件绘制多张图
May 13 Python
pytorch 查看cuda 版本方式
Jun 23 Python
教你用python控制安卓手机
May 13 Python
聊聊pytorch测试的时候为何要加上model.eval()
May 23 Python
Python中对象迭代与反迭代的技巧总结
Sep 17 #Python
发布你的Python模块详解
Sep 15 #Python
Python selenium 三种等待方式解读
Sep 15 #Python
玩转python selenium鼠标键盘操作(ActionChains)
Apr 12 #Python
Python selenium文件上传方法汇总
Nov 19 #Python
Python selenium如何设置等待时间
Sep 15 #Python
Python selenium 父子、兄弟、相邻节点定位方式详解
Sep 15 #Python
You might like
PHP COOKIE设置为浏览器进程
2009/06/21 PHP
PHP为表单获取的URL 地址预设 http 字符串函数代码
2010/05/26 PHP
php封装的smarty类完整实例
2016/10/19 PHP
php实现图片按比例截取的方法
2017/02/06 PHP
脚本安需导入(装载)的三种模式的对比
2007/06/24 Javascript
asp(javascript)全角半角转换代码 dbc2sbc
2009/08/06 Javascript
IE 条件注释详解总结(附实例代码)
2009/08/29 Javascript
js或css实现滚动广告的几种方案
2010/01/28 Javascript
ASP.NET jQuery 实例2 (表单中使用回车在TextBox之间向下移动)
2012/01/13 Javascript
Array栈方法和队列方法的特点说明
2014/01/24 Javascript
js判断一个字符串是否包含一个子串的方法
2015/01/26 Javascript
js实现获取当前时间是本月第几周的方法
2015/08/11 Javascript
Angular.js与Bootstrap相结合实现表格分页代码
2016/04/12 Javascript
thinkjs之页面跳转同步异步操作
2017/02/05 Javascript
教你快速搭建Node.Js服务器的方法教程
2017/03/30 Javascript
mui上拉加载功能实例详解
2017/04/13 Javascript
纯JS实现出生日期[年月日]下拉菜单效果
2018/06/01 Javascript
解决angularjs service中依赖注入$scope报错的问题
2018/10/02 Javascript
JavaScript实现公告栏上下滚动效果
2020/03/13 Javascript
[05:26]TI10典藏宝瓶套装外观展示
2020/07/03 DOTA
[52:02]完美世界DOTA2联赛PWL S2 FTD.C vs SZ 第一场 11.27
2020/11/30 DOTA
从零学python系列之从文件读取和保存数据
2014/05/23 Python
Python实现对excel文件列表值进行统计的方法
2015/07/25 Python
基于python实现学生管理系统
2018/10/17 Python
在Pycharm中设置默认自动换行的方法
2019/01/16 Python
Python替换月份为英文缩写的实现方法
2019/07/15 Python
Django CBV模型源码运行流程详解
2020/08/17 Python
HTML5计时器小例子
2013/10/15 HTML / CSS
html5视频常用API接口的实战示例
2020/03/20 HTML / CSS
简单说下OSPF的操作过程
2014/08/13 面试题
酒店员工培训方案
2014/06/02 职场文书
政府法律服务方案
2014/06/14 职场文书
学校花圃的标语
2014/06/18 职场文书
2015年会计工作总结范文
2015/05/26 职场文书
详解Python中__new__方法的作用
2022/03/31 Python
未发现nvidia显卡怎么办?Win11系统中未检测到nvidia显卡解决教程
2022/04/08 数码科技