Python的正则表达式使用

Python的正则表达式使用

创建一个30个空格的变量:

In [1]: str = ' ' * 30

In [2]: str
Out[2]: '                              '

引入正则库:

In [4]: import re

In [5]: re
Out[5]: <module 're' from '/anaconda3/lib/python3.6/re.py'>

创建一个字串:

In [7]: text = str + "age: ..."

In [8]: text
Out[8]: '                              age: ...'

一个一个替换空格:

In [9]: re.sub(r'\s','x',text)
Out[9]: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxage:x...'

替换一个或多个空格:

In [10]: re.sub(r'\s+','x',text)
Out[10]: 'xage:x...'

在正则表达式里面使用变量:

In [14]: re.sub(r"" + str,'x',text)
Out[14]: 'xage: ...'

In [15]:

以上。

My Github Page: https://github.com/liweinan

Powered by Jekyll and Theme by solid

If you have any question want to ask or find bugs regarding with my blog posts, please report it here:
https://github.com/liweinan/liweinan.github.io/issues