Reputation: 23
I have a string that I need to reconstruct with new values. The string looks like this:
log = "2019-06-25T11:09:59+00:00 15.24.137.43 printer: powered up"
I have a list that already contains the values:
list1 = ["2019-06-25T11:09:59+00:00", "15.24.137.43", "printer", "powered up"]
I have another list that contains the values that I am going to replace in the original log:
list2 = ["date", "ip_address", "device", "event"]
I have tried the following in 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)
What I want to obtain is the reconstructed log such as:
'date ip_address device event'
It seems like the replace()
method doesn't keep changes. When I print the log, on the last line, it prints the original log which is:
2019-06-25T11:09:59+00:00 15.24.137.43 printer: powered up
Do you have any idea on how can I keep the changes on the log, so I can have it fully reconstructed at the end? I would appreciate it if anyone would help! Thanks!
Upvotes: 0
Views: 331
Reputation: 1039
String in python are immutable and replace
return new string - it doesn't update old value. Try this:
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)
Upvotes: 4