如何使用正则表达式替换模式?

2024-10-04 03:17:58 发布

您现在位置:Python中文网/ 问答频道 /正文

string1 = "2018-Feb-23-05-18-11"

我想替换字符串中的特定模式。 输出应该是2018-Feb-23-5-18-11。你知道吗

如何使用re.sub来实现这一点?你知道吗

Example:
import re
output = re.sub(r'10', r'20', "hello number 10, Agosto 19")
#hello number 20, Agosto 19

正在从datetime模块获取当前的\u datetime。我正在将获取的datetime格式化为所需的格式。你知道吗

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%Y-%b-%d-%I-%M-%S")

我想,回复sub是最好的方法。你知道吗

ex1 : 
string1 = "2018-Feb-23-05-18-11"
output : 2018-Feb-23-5-18-11

ex2 : 
string1 = "2018-Feb-23-05-8-11"
output : 2018-Feb-23-5-08-11

Tags: 模块字符串importrenumberhellooutputdatetime
2条回答

在处理日期和时间时,最好首先将日期转换为Pythondatetime对象,而不是尝试使用正则表达式更改它。然后可以更容易地将其转换回所需的日期格式。你知道吗

但是对于前导零,formatting options只提供前导零选项,因此为了获得更大的灵活性,有时需要将格式与标准Python格式混合使用:

from datetime import datetime

for test in ['2018-Feb-23-05-18-11', '2018-Feb-23-05-8-11', '2018-Feb-1-0-0-0']:
    dt = datetime.strptime(test, '%Y-%b-%d-%H-%M-%S')
    print '{dt.year}-{}-{dt.day}-{dt.hour}-{dt.minute:02}-{dt.second}'.format(dt.strftime('%b'), dt=dt)

给你:

2018-Feb-23-5-18-11
2018-Feb-23-5-08-11
2018-Feb-1-0-00-0

它使用.format()函数来组合各个部分。它允许传递对象,然后格式化可以直接访问对象的属性。唯一需要使用strftime()格式化的部分是月份。你知道吗


这将得到相同的结果:

import re

for test in ['2018-Feb-23-05-18-11', '2018-Feb-23-05-8-11', '2018-Feb-1-0-0-0']:
    print re.sub(r'(\d+-\w+)-(\d+)-(\d+)-(\d+)-(\d+)', lambda x: '{}-{}-{}-{:02}-{}'.format(x.group(1), int(x.group(2)), int(x.group(3)), int(x.group(4)), int(x.group(5))), test)

使用datetime模块。你知道吗

例如:

import datetime

string1 = "2018-Feb-23-05-18-11"
d = datetime.datetime.strptime(string1, "%Y-%b-%d-%H-%M-%S")
print("{0}-{1}-{2}-{3}-{4}-{5}".format(d.year, d.strftime("%b"), d.day, d.hour, d.minute, d.second))

输出:

2018-Feb-23-5-18-11

相关问题 更多 >