str.replace()和re.sub()/calendar.month_abbr/re.subn()/upper和lower和capitalize/贪婪匹配和费贪婪匹配/re.S和re.DOTALL 笔记

str.replace()可以进行简单的替换

>>> a = 'one.txt, index.py, index.php, index.html, index.js'
>>> a.replace('one.txt', 'index.css')
'index.css, index.py, index.php, index.html, index.js'

re.sub()可以使用正则替换

>>> import re
>>> a
'one.txt, index.py, index.php, index.html, index.js'
>>> re.sub(r'\.[a-z]+', '.csv', a)
'one.csv, index.csv, index.csv, index.csv, index.csv'

# re.sub还可以保留原字符串的大小写(不过要麻烦一些)

import re
text1 = 'UPPER PYTHON, lower python, Capitalize Python'
def python_deal(word):
    def replace_word(m):
        text = m.group()  # 接收re.sub()函数第一个参数匹配的内容
        # 进行word(新字符串)的转换
        if text.isupper():
            return word.upper()
        elif text.islower():
            return word.lower()
        elif text[0].isupper():
            return word.capitalize()
        else:
            return word
    return replace_word
# re.IGNORECASE 可以忽略大小写的区别,还有值得注意的是re.IGNORECASE的键(flags)必须写
# re.sub()第二个参数使用函数的话,里面必须是回调函数,而且回调函数的参数必然是re.sub第一个参数匹配的内容
print(re.sub('python', python_deal('new_python'), text1, flags=re.IGNORECASE))

使用calendar.month_abbr

# 可以将字符串/数字进行转换成为对应的因为月份

>>> from calendar import month_abbr
>>> month_abbr[int('12')]
'Dec'

使用re.subn()

# 进行统计进行替换的次数

import re
text1 = 'namejr04/15/1996, abc11/17/2018, qwe11/17/2017'
# 匹配时间字符
date_sub = re.compile(r'(\d+)/(\d+)/(\d+)')
new_sub, n = date_sub.subn(r'\3-\1-\2', text1) # 获取新替换的字符串和替换的次数
print(new_sub)
print(n)
"""
D:\笔记\python电子书\Python3>python index.py
namejr1996-04-15, abc2018-11-17, qwe2017-11-17
3
"""

upper()/lower()/capitalize()转换字母

>>> a = 'hello world'
>>> b = a.upper() # 将全部字母转换为大写
>>> b
'HELLO WORLD'
>>> c = b.lower() # 将全部字母转换为小写
>>> c
'hello world'
>>> d = c.capitalize() # 将首字母进行大写,其他字母转换为小写
>>> d
'Hello world'


贪婪模式和费贪婪模式

# 贪婪匹配会匹配到尽可能多的字符

>>> a
"i love 'my father' and 'my mother' and 'my brothers'"
>>> re.findall(r'\'(.*)\'', a) # 匹配到的"'"是最前面一个和最后面一个
["my father' and 'my mother' and 'my brothers"]

# 非贪婪匹配匹配到的尽可能少的字符(满足匹配条件的情况下)
>>> a
"i love 'my father' and 'my mother' and 'my brothers'"
>>> re.findall(r'\'(.*?)\'', a) # 匹配到的是每一对单引号里面的内容
['my father', 'my mother', 'my brothers']

使用re.S/re.DOTALL进行换行符的匹配

import re
a = """*onrtsdddddddddd
onehellow
addd
*"""
# 使用re.S和re.DOTALL匹配出来的内容都是一样的,都表示包括换行符内容的匹配
str_patter1 = re.compile(r'\*(.*)\*', re.DOTALL)
print(str_patter1.findall(a))
"""
D:\笔记\python电子书\Python3>python index.py
['onrtsdddddddddd\nonehellow\naddd\n']
"""

猜你喜欢

转载自www.cnblogs.com/namejr/p/9976584.html