对python 中re.sub,replace(),strip()的区别详解

作者:lwgkzl 时间:2022-07-17 21:33:03 

1.strip():

str.strip([chars]);去除字符串前面和后面的所有设置的字符串,默认为空格

chars -- 移除字符串头尾指定的字符序列。


st = "  hello  "
st = st.strip()
print(st+"end")

输出:

对python 中re.sub,replace(),strip()的区别详解

如果设置了字符序列的话,那么它会删除,字符串前后出现的所有序列中有的字符。但不会清除空格。


st = "hello"
st = st.strip('h,o,e')
print(st)

因为,在h去除之后,e便出现在首位,所以e也会被去除,最终得到的答案就是ll

对python 中re.sub,replace(),strip()的区别详解

2.replace():

替代字符串中的某一些子串为另一些字符。 str.replace(old, new[, max])

old -- 将被替换的子字符串。

new -- 新字符串,用于替换old子字符串。

max -- 可选字符串, 替换不超过 max 次

替换某一个子串:


st = "i want a apple"
st = st.replace("apple","mice")
print(st)

规定最大替换次数:


st = "i want a apple and a apple"
st = st.replace("apple","mice",1)
print(st)

对python 中re.sub,replace(),strip()的区别详解

3.re.sub()

替换字符串中的某些子串,可以用正则表达式来匹配被选子串。

re.sub(pattern, repl, string, count=0, flags=0)

pattern:表示正则表达式中的模式字符串;

repl:被替换的字符串(既可以是字符串,也可以是函数);

string:要被处理的,要被替换的字符串;

count:匹配的次数, 默认是全部替换

如下,用正则方便多了,匹配所有连续出现的数字(把2019换成了danshenggou:):


st = "hello 2019"
st = re.sub("([0-9]+)","danshengou",st)
print(st)

对python 中re.sub,replace(),strip()的区别详解

匹配连续出现两次的a,并把它换成一个。


st = "hello aabbaa"
st = re.sub("(a{2})","a",st)
print(st)

对python 中re.sub,replace(),strip()的区别详解

来源:https://blog.csdn.net/lwgkzl/article/details/85544871

标签:python,re.sub,replace,strip
0
投稿

猜你喜欢

  • javascript 45种缓动效果(一)

    2009-09-19 18:30:00
  • Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签

    2022-12-10 13:55:18
  • Python实现的十进制小数与二进制小数相互转换功能

    2022-02-17 16:24:39
  • 详解Python中的路径问题

    2021-06-05 08:48:45
  • 初窥交互设计

    2009-10-10 10:52:00
  • MySQL 数据库优化的具体方法说明

    2024-01-15 08:26:13
  • Python3 单行多行万能正则匹配方法

    2023-03-22 13:47:33
  • python中注释用法简单示例

    2022-10-24 05:04:09
  • MYSQL实现连续签到功能断签一天从头开始(sql语句)

    2024-01-22 16:35:11
  • Jaspersoft Studio添加mysql数据库配置步骤

    2024-01-17 01:13:26
  • php中正则替换函数ereg_replace用法实例

    2023-06-13 03:03:51
  • tensorflow基于Anaconda环境搭建的方法步骤

    2022-11-04 10:12:58
  • python替换字符串中的子串图文步骤

    2021-06-23 22:02:47
  • 在vue-cli3中使用axios获取本地json操作

    2023-07-02 17:07:12
  • python为QT程序添加图标的方法详解

    2021-05-16 15:56:08
  • Python基于回溯法子集树模板实现8皇后问题

    2023-09-25 08:34:45
  • python代码实现猜拳小游戏

    2023-10-16 19:00:46
  • Python实现的基数排序算法原理与用法实例分析

    2023-11-11 10:15:12
  • Python不支持 i ++ 语法的原因解析

    2022-02-07 12:16:49
  • MySQL命令无法输入中文问题的解决方式

    2024-01-15 19:29:54
  • asp之家 网络编程 m.aspxhome.com