根据位置替换字符串中的元素是否更有效?

Is there a more efficient to replace the elements in a string based on their position?

我有以下字符串 '2022-01-03 20:04:22',我想将最后两个元素更改为“00”,因此它看起来像这样 '2022-01-03 20:04:00'

我摸索出以下方法:

s = '2022-01-03 20:04:22'
print(s)

n = len(s) - 2
print(n)

r = '00'
print(r)

s = s[0:n] + r
print(s)


Output:
2022-01-03 20:04:22
17
00
2022-01-03 20:04:00

它完成了工作,但我觉得他们应该是更好的方法。

例如,我首先尝试了这个:

s = '2022-01-03 20:04:22'
s = s.replace(s[-2:], '00')

但我最终得到的是:2000-01-03 20:04:00 其中年份中的“22”也更改为“00”。

我现在明白 s[-2:] 从索引中提取值 '22' 然后它在字符串中两次找到这个值(在 2022 年和日期时间的秒部分) 并将它们替换为“00”。

到目前为止,我还没有找到替换字符串中特定位置的字符的解决方案。

字符串切片如何:

s = s[:-2] + '00'

输出:

'2022-01-03 20:04:00'

由于您使用的是日期和时间,在这种情况下,replace() 方法可以为您提供帮助。要四舍五入到分钟,如您的示例所示,您可以这样做:

from dateutil import parser
foo = parser.parse("2022-01-03 20:04:22")
foo = foo.replace(microsecond=0, second=0)

将其打印回字符串:

foo.strftime("%Y-%m-%d %H:%M:%S")

会给你:

'2022-01-03 20:04:00'

我可以看到给定的字符串是日期时间类型。 您可以使用下面的代码来获得所需的结果。

from datetime import datetime

s = '2022-01-03 20:04:22'

date_object = datetime.strftime(datetime.fromisoformat(s),"%Y-%m-%d %H:%M:00")

print(date_object)