0

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!

1
  • .replace() is not an inplace method Commented Jun 24, 2021 at 21:09

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.