How to retrieve and replace in python (example analysis)

乌拉乌拉~
Release: 2018-08-20 17:57:07
Original
2737 people have browsed it

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)
Copy after login

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
Copy after login

The execution results of the above example are as follows:

电话号码是:  2004-959-559 
电话号码是 :  2004959559
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template