【问题标题】:Python replace() method doesn't keep changesPython replace() 方法不保留更改
【发布时间】:2021-09-08 08:40:43
【问题描述】:

我有一个需要用新值重构的字符串。 字符串如下所示:

log = "2019-06-25T11:09:59+00:00 15.24.137.43 printer: powered up"

我有一个已经包含值的列表:

list1 = ["2019-06-25T11:09:59+00:00",  "15.24.137.43", "printer", "powered up"]

我有另一个列表,其中包含我要在原始日志中替换的值:

list2 = ["date", "ip_address", "device", "event"]

我在 python 中尝试过以下操作:

list2_iteration = 0
for field in list1:
    if(log.find(field) != -1):
        #print(field)
        log.replace(field,list2[list2_iteration])
    list2_iteration += 1
print(log)

我想要得到的是重构后的日志如:

'date ip_address device event'

replace() 方法似乎没有保留更改。当我打印日志时,在最后一行,它会打印原始日志:

2019-06-25T11:09:59+00:00 15.24.137.43 printer: powered up

您知道如何将更改保留在日志中,以便在最后完全重建它吗? 如果有人能提供帮助,我将不胜感激! 谢谢!

【问题讨论】:

  • .replace() 不是就地方法

标签: python string replace find


【解决方案1】:

python 中的字符串是不可变的,replace return 新字符串 - 它不会更新旧值。试试这个:

list2_iteration = 0
for field in list1:
    if(log.find(field) != -1):
        #print(field)
        log = log.replace(field,list2[list2_iteration])
    list2_iteration += 1
print(log)

【讨论】:

    猜你喜欢
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2022-01-05
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多