Python replace() 方法不保留更改
Python replace() method doesn't keep changes
我有一个字符串需要用新值重建。
字符串如下所示:
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
您是否知道如何将更改保留在日志中,这样我才能在最后完全重建它?
如果有人愿意提供帮助,我将不胜感激!
谢谢!
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)
我有一个字符串需要用新值重建。 字符串如下所示:
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
您是否知道如何将更改保留在日志中,这样我才能在最后完全重建它? 如果有人愿意提供帮助,我将不胜感激! 谢谢!
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)