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']
"""

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM