How to use Python to query and replace a text string
This article mainly introduces how to use Python to query and replace a text string, the article is very detailed, has a certain reference value, interested friends must read it!
How to query and replace a text string with Python?
Answer: you can use the sub () function in the re module or the subn () function to query and replace
Format: sub (replacement, string [, count=0]) (replacement is the text to be replaced, string is the text to be replaced, and count is an optional parameter, which refers to the maximum number of replacements)
> import re > p=re.compile ('blue | white | red') > print (p.sub (' colour','blue socks and redshoes')) colour socks and colourshoes > print (p.sub ('colour','blue socks and redshoes', count=1)) colour socks and redshoes
The subn () method performs the same effect as sub (), but it returns a two-dimensional array, including the new string after replacement and the total number of substitutions
The above is all the contents of the article "how to use Python to query and replace a text string". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!