Python/python14/5.md

57 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# re.sub
实战过程中,我们很多时候需要替换字符串中的字符,这时候就可以用到 `def sub(pattern, repl, string, count=0, flags=0) ` 函数了re.sub 共有五个参数。其中三个必选参数pattern, repl, string ; 两个可选参数count, flags .
具体参数意义如下:
| 参数 | 描述 |
| ------- | ------------------------------------------------------------- |
| pattern | 表示正则中的模式字符串 |
| repl | repl就是replacement被替换的字符串的意思 |
| string | 即表示要被处理,要被替换的那个 string 字符串 |
| count | 对于pattern中匹配到的结果count可以控制对前几个group进行替换 |
| flags | 正则表达式修饰符 |
具体使用可以看下下面的这个实例,注释都写的很清楚的了,主要是注意一下,第二个参数是可以传递一个函数的,这也是这个方法的强大之处,例如例子里面的函数 `convert` ,对传递进来要替换的字符进行判断,替换成不同的字符。
```python
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import re
a = 'Python*Android*Java-888'
# 把字符串中的 * 字符替换成 & 字符
sub1 = re.sub('\*', '&', a)
print(sub1)
# 把字符串中的第一个 * 字符替换成 & 字符
sub2 = re.sub('\*', '&', a, 1)
print(sub2)
# 把字符串中的 * 字符替换成 & 字符,把字符 - 换成 |
# 1、先定义一个函数
def convert(value):
group = value.group()
if (group == '*'):
return '&'
elif (group == '-'):
return '|'
# 第二个参数,要替换的字符可以为一个函数
sub3 = re.sub('[\*-]', convert, a)
print(sub3)
```
输出的结果:
```txt
Python&Android&Java-888
Python&Android*Java-888
Python&Android&Java|888
```