re.sub
In actual combat, we often need to replace characters in a string. At this time, we can use the def sub(pattern, repl, string, count=0, flags=0) function. There are five re.sub parameter. Three of the required parameters: pattern, repl, string; two optional parameters: count, flags.
The meaning of the specific parameters is as follows:
Parameter | Description |
pattern | Represents the pattern string in the regular expression |
repl | repl, is replacement, the meaning of the replaced string |
string | means that it needs to be processed , the string string to be replaced |
count | For the matched results in the pattern, count can control the replacement of the first few groups |
flags | Regular expression modifier |
For specific usage, you can see the example below. The comments are very detailed. It's clear. The main thing to note is that the second parameter can be passed a function. This is also the power of this method. For example, the function convert in the example judges the characters passed in to be replaced and replaces them with different ones. character.
#!/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)
Output result:
Python&Android&Java-888 Python&Android*Java-888 Python&Android&Java|888