Python常用字符串替换函数strip、replace及sub用法示例


Posted in Python onMay 21, 2018

本文实例讲述了Python常用字符串替换函数strip、replace及sub用法。分享给大家供大家参考,具体如下:

今天在做一道今年秋季招聘题目的时候遇上了一个替换的问题,题目看起来好长好复杂啊,真的,一时间,我看了好几遍也没看懂,其实实质很简单,就是需要把给定的一个字符串里面的指定字符替换成一些指定的内容就行了,这样首选当然是字典了,没有之一,题目很简单就不写出来了,在这里花了一点时间专门总结了一下字符串的替换的几个常用的函数,希望也能帮到有需要的人,自己也是当做一个学习的记录,好了,在这里就不多说什么了,在代码中该说的都说了,直接看程序:

#!/usr/bin/env python
# coding:utf-8
import re
'''''
功能:对常见的几种字符串处理函数进行测试使用学习
Author:沂水寒城
'''
def str_test():
  str_list=['We are family!!!', '00 11 22 33 44 55 66 77 88 99',
       'Trouble is a friend!!!Trouble is a friend!!!', 'LoveLoveLove']
  str_dict={
    '!!!':'$$$',
    ' ':'@',
    'T':'t',
    'L':'&'
  }
  #使用replace
  '''''
  基本用法:对象.replace(rgExp,replaceText,max)
  rgExp和replaceText是必须要有的,max是可选的参数
  '''
  str_list1=str_list
  res_list=[]
  for one_str in str_list1:
    for key in str_dict:
      one_str = one_str.replace(key, str_dict[key])
    res_list.append(one_str)
  print '**************replace替换结果为:*********************'
  print str_list1
  print res_list
  #使用re
  '''''
  re.sub()有5个参数,三个必选参数pattern,repl,string;两个可选参数count,flags
  re.sub(pattern,repl,string,count,flags)
  pattern:表示正则表达式中的模式字符串;
  repl:被替换的字符串,或者是一个方法(既可以是字符串,也可以是函数);
  当repl为字符串的时候,也就是需要 将string中与pattern匹配的字符串都替换成repl
  当repl为方法的时候,就必须是一个带有一个参数,且参数为MatchObject类型的方法,该方法需要返回一个字符串。
  string:要被处理的,要被替换的字符串;
  count:指的是最大的可以被替换的匹配到的字符串的个数,默认为0,就是所有匹配到的字符串。
  flgas:标志位
  '''
  str_list2=str_list
  res_list=[]
  pattern_rule=re.compile(r'!!!')
  for one_str in str_list2:
    one_str = re.sub(pattern_rule, '$$$', one_str)
    res_list.append(one_str)
  print '**************sub替换结果为:*********************'
  print str_list2
  print res_list
  #使用strip()
  '''''
  个人使用strip()很久了,感觉这个函数在一些事比如字符串末尾换行符去除等方面出奇的好用,
  它并不算是一个纯正意义上跟上面两个函数类似的字符串处理的函数,但是用于字符串尾部删除等方面的时候
  效果还是很不错的
  '''
  str_list3=str_list
  res_list=[]
  for one_str in str_list3:
    one_str=one_str.strip('!!!')
    res_list.append(one_str)
  print '**************strip替换结果为:*********************'
  print str_list3
  print res_list
str_test()

结果如些下:

**************replace替换结果为:*********************
['We are family!!!', '00 11 22 33 44 55 66 77 88 99', 'Trouble is a friend!!!Trouble is a friend!!!', 'LoveLoveLove']
['We@are@family$$$', '00@11@22@33@44@55@66@77@88@99', 'trouble@is@a@friend$$$trouble@is@a@friend$$$', '&ove&ove&ove']
**************sub替换结果为:*********************
['We are family!!!', '00 11 22 33 44 55 66 77 88 99', 'Trouble is a friend!!!Trouble is a friend!!!', 'LoveLoveLove']
['We are family$$$', '00 11 22 33 44 55 66 77 88 99', 'Trouble is a friend$$$Trouble is a friend$$$', 'LoveLoveLove']
**************strip替换结果为:*********************
['We are family!!!', '00 11 22 33 44 55 66 77 88 99', 'Trouble is a friend!!!Trouble is a friend!!!', 'LoveLoveLove']
['We are family', '00 11 22 33 44 55 66 77 88 99', 'Trouble is a friend!!!Trouble is a friend', 'LoveLoveLove']

这些东西应该算得上是很顺手的小工具了,特别是在一些应用中能起到四两拨千斤的作用,也许是夸张了哈,但是就是很喜欢这几个小工具,所以就写出来分享一下,不足之处还望多多指教,大家共同学习共同进步!

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python logging日志模块的详解
Oct 29 Python
利用Tkinter和matplotlib两种方式画饼状图的实例
Nov 06 Python
python中如何正确使用正则表达式的详细模式(Verbose mode expression)
Nov 08 Python
详解python中asyncio模块
Mar 03 Python
Python解决八皇后问题示例
Apr 22 Python
Flask Web开发入门之文件上传(八)
Aug 17 Python
对Python实现简单的API接口实例讲解
Dec 10 Python
Python可迭代对象操作示例
May 07 Python
Django CBV与FBV原理及实例详解
Aug 12 Python
TensorFlow索引与切片的实现方法
Nov 20 Python
Python图像处理库PIL中图像格式转换的实现
Feb 26 Python
OpenCV-Python实现轮廓拟合
Jun 08 Python
Python下使用Scrapy爬取网页内容的实例
May 21 #Python
python 每天如何定时启动爬虫任务(实现方法分享)
May 21 #Python
对python抓取需要登录网站数据的方法详解
May 21 #Python
深入浅析python 中的匿名函数
May 21 #Python
python3 selenium 切换窗口的几种方法小结
May 21 #Python
python selenium 对浏览器标签页进行关闭和切换的方法
May 21 #Python
pytorch cnn 识别手写的字实现自建图片数据
May 20 #Python
You might like
使用apache模块rewrite_module (转)
2007/02/14 PHP
PHP mb_convert_encoding文字编码的转换函数介绍
2011/11/10 PHP
PHP三元运算符的结合性介绍
2012/01/10 PHP
PHP文件上传主要代码讲解
2013/09/30 PHP
PHPExcel内存泄漏问题解决方法
2015/01/23 PHP
PHP导出带样式的Excel示例代码
2016/08/28 PHP
javascript DOM编程实例(智播客学习)
2009/11/23 Javascript
Firebug入门指南(Firefox浏览器)
2010/08/21 Javascript
JS中confirm,alert,prompt函数区别分析
2011/01/17 Javascript
JavaScript高级程序设计(第3版)学习笔记10 再访js对象
2012/10/11 Javascript
jQuery插件Validation快速完成表单验证的方式
2016/07/28 Javascript
JS实现DIV高度自适应窗口示例
2017/02/16 Javascript
vue.js 添加 fastclick的支持方法
2018/08/28 Javascript
layui表格 列自动适应大小失效的解决方法
2019/09/06 Javascript
微信小程序实用代码段(收藏版)
2019/12/17 Javascript
微信小程序实现上传多张图片、删除图片
2020/07/29 Javascript
python中精确输出JSON浮点数的方法
2014/04/18 Python
Python THREADING模块中的JOIN()方法深入理解
2015/02/18 Python
python制作websocket服务器实例分享
2016/11/20 Python
详解python调度框架APScheduler使用
2017/03/28 Python
Python语言描述随机梯度下降法
2018/01/04 Python
python 用正则表达式筛选文本信息的实例
2018/06/05 Python
Python3中的列表生成式、生成器与迭代器实例详解
2018/06/11 Python
用python中的matplotlib绘制方程图像代码
2019/11/21 Python
Python 词典(Dict) 加载与保存示例
2019/12/06 Python
python+selenium+Chrome options参数的使用
2020/03/18 Python
Django 拼接两个queryset 或是两个不可以相加的对象实例
2020/03/28 Python
python右对齐的实例方法
2020/07/05 Python
CSS3绘制超炫的上下起伏波动进度加载动画
2016/04/21 HTML / CSS
免费获得微软MCSD证书赶快行动吧!
2012/11/13 HTML / CSS
Pretty You London官网:英国拖鞋和睡衣品牌
2019/05/08 全球购物
Gerry Weber德国官网:优质女性时装,德国最大的时装公司之一
2019/11/02 全球购物
golang中的空接口使用详解
2021/03/30 Python
mysql 8.0.24 安装配置方法图文教程
2021/05/12 MySQL
MySQL Router实现MySQL的读写分离的方法
2021/05/27 MySQL
详解Redis集群搭建的三种方式
2021/05/31 Redis