In this article, let’s learn about python retrieval and replacement. Some friends may have just come into contact with the python programming language and do not have a special understanding of this aspect, but it doesn’t matter. The following article will introduce you to this knowledge.
Retrieve and replace
Python's re module provides re.sub for replacing matches in a string.
Syntax is as follows:
re.sub(pattern, repl, string, count=0, flags=0)
Parameters is as follows:
pattern: Pattern string in regular expression.
repl: The string to be replaced, or it can be a function.
string : The original string to be searched and replaced.
count: The maximum number of substitutions after pattern matching. The default value is 0, which means replacing all matches.
Let’s give an example, the example is as follows:
#!/usr/bin/python # -*- coding: UTF-8 -*- import re phone = "2004-959-559 # 这是一个国外电话号码" # 删除字符串中的 Python注释 num = re.sub(r'#.*$', "", phone) print "电话号码是: ", num # 删除非数字(-)的字符串 num = re.sub(r'\D', "", phone) print "电话号码是 : ", num
The execution results of the above example are as follows:
电话号码是: 2004-959-559 电话号码是 : 2004959559
The above is all the content described in this article , this article mainly introduces the relevant knowledge of retrieval and replacement in python. I hope you can use the information to understand the above content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.
For more related knowledge, please visit the Python tutorial column on the php Chinese website.
The above is the detailed content of How to retrieve and replace in python (example analysis). For more information, please follow other related articles on the PHP Chinese website!