python字符串替换函数_Python正则替换字符串函数re.sub

python re.sub属于python正则的标准库,主要是的功能是用正则匹配要替换的字符串

然后把它替换成自己想要的字符串的方法

re.sub 函数进行以正则表达式为基础的替换工作

1 #!/usr/bin/env python

2 #encoding: utf-8

3 import re

4 url = 'https://113.215.20.136:9011/113.215.6.77/c3pr90ntcya0/youku/6981496DC9913B8321BFE4A4E73/0300010E0C51F10D86F80703BAF2B1ADC67C80-E0F6-4FF8-B570-7DC5603F9F40.flv'

5 pattern = re.compile(r'(?

6 print pattern.findall(url)

7 out = re.sub(pattern, '127.0.0.1', url)

8 print out

执行结果:

1 [root@CentOS-7 shu]# python re_sub.py

2 ['113.215.20.136', '113.215.6.77']

3 https://127.0.0.1:9011/127.0.0.1/c3pr90ntcya0/youku/6981496DC9913B8321BFE4A4E73/0300010E0C51F10D86F80703BAF2B1ADC67C80-E0F6-4FF8-B570-7DC5603F9F40.flv

re.sub 函数详解:

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

re.sub 用于替换字符串的匹配项。如果没有匹配到规则,则原字符串不变。

第一个参数:规则

第二个参数:替换后的字符串

第三个参数:字符串

第四个参数:替换个数。默认为0,表示每个匹配项都替换

还可以这样:

tempstr = "hello you hello python are you ok"

import re

rex = r'(hello|Use)'

print re.sub(rex,"Bye",tempstr)

python中最简单的替换字符串 ,利用本身的函数:

#最简单的方法使用replace()

tempstr = "hello you hello python are you ok"

print tempstr.replace("you","python")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python字符串替换函数有很多,这里介绍其中的几个: 1. `replace()`函数 `replace()`函数可以将字符串中的某个子串替换成指定的字符串。该函数的语法如下: ```python str.replace(old, new[, count]) ``` 其中: - `old`:要被替换的子串。 - `new`:用于替换 `old` 的新字符串。 - `count`:可选参数,指定替换的次数。 示例: ```python my_str = "Hello, World!" new_str = my_str.replace("World", "Python") print(new_str) # 输出:Hello, Python! ``` 2. `translate()`函数 `translate()`函数可以将字符串中的某些字符替换成指定的字符。该函数的语法如下: ```python str.translate(table) ``` 其中: - `table`:翻译表,可以使用 `maketrans()` 函数生成。 示例: ```python my_str = "Hello, World!" table = str.maketrans("o", "0") new_str = my_str.translate(table) print(new_str) # 输出:Hell0, W0rld! ``` 3. `sub()`函数 `sub()`函数是 `re` 模块中的函数,用于正则表达式替换。该函数的语法如下: ```python re.sub(pattern, repl, string, count=0, flags=0) ``` 其中: - `pattern`:正则表达式。 - `repl`:用于替换字符串。 - `string`:要被替换字符串。 - `count`:可选参数,指定替换的次数。 - `flags`:可选参数,指定正则表达式的匹配模式。 示例: ```python import re my_str = "Hello, 123!" new_str = re.sub(r"\d+", "World", my_str) print(new_str) # 输出:Hello, World! ``` 以上是常用的几个字符串替换函数,根据需求选择合适的函数即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值