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


原文地址:https://www.cnblogs.com/zzy-9318/p/10457921.html