Python之字符串搜索和替換


簡單直接使用 str.replace()
text="zzy is a beautiful boy"
print(text.replace("boy","girl"))  # zzy is a beautiful girl
對於復雜的模式,請使用 re 模塊中的 sub() 函數
# 假設你想將形式為 11/27/2018 的日期字符串改成 2018-11-27
import re
date="11/27/2018"
print(re.sub(r"(\d+)/(\d+)/(\d+)",r"\3-\1-\2",date))  # 2018-11-27
# sub() 函數中的第一個參數是被匹配的模式,第二個參數是替換模式。反斜杠數字比如 \3 指向前面模式的捕獲組號
如果你打算用相同的模式做多次替換,考慮先編譯它來提升性能
datepat=re.compile(r"(\d+)/(\d+)/(\d+)")
print(datepat.sub(r"\3-\1-\2",date))  # 2018-11-27
對於更加復雜的替換,不再是簡單是的把“/”替換成”-“,也許是變成”Today is 27 Nov 2018.“可以傳遞一個替換回調函數來代替,
from calendar import month_abbr

def change_date(data):
    month=month_abbr[int(data.group(1))]
    return "Today is {} {} {}".format(data.group(3),month,data.group(2))

print(datepat.sub(change_date,date))  # Today is 2018 Nov 27

補充:calendar

def get_month(year, month):
    return calendar.month(year, month)

#返回指定年的日歷
def get_calendar(year):
    return calendar.calendar(year)

#判斷某一年是否為閏年,如果是,返回True,如果不是,則返回False
def is_leap(year):
    return calendar.isleap(year)

#返回某個月的weekday的第一天和這個月的所有天數
def get_month_range(year, month):
    return calendar.monthrange(year, month)

#返回某個月以每一周為元素的序列
def get_month_calendar(year, month):
    return calendar.monthcalendar(year, month)

# 返回指定年的日歷
def get_calendar(year):
    return calendar.calendar(year)

#判斷某一年是否為閏年,如果是,返回True,如果不是,則返回False
def is_leap(year):
    return calendar.isleap(year)

#返回某個月的weekday的第一天和這個月的所有天數
def get_month_range(year, month):
    return calendar.monthrange(year, month)

#返回某個月以每一周為元素的序列
def get_month_calendar(year, month):
    return calendar.monthcalendar(year, month)

year = 2013
month = 8
test_month = get_month(year, month)
print(test_month)
print('#' * 50)
#print(get_calendar(year))
print('{0}這一年是否為閏年?:{1}'.format(year, is_leap(year)))
print(get_month_range(year, month))
print(get_month_calendar(year, month))

"""
"""
 August 2013
Mo Tu We Th Fr Sa Su
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

##################################################
2013這一年是否為閏年?:False
(3, 31)
[[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 31, 0]]

Process finished with exit code 0
"""

 




免責聲明!

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



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