Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a word from text in Python

Tags:

python

I have this string "IP 1.2.3.4 is currently trusted in the white list, but it is now using a new trusted certificate." in a log file. What I need to do is look for this message and extract the IP address (1.2.3.4) from the log file.

import os
import shutil
import optparse
import sys

def main():
    file = open("messages", "r")
    log_data = file.read()
    file.close()

    search_str = "is currently trusted in the white list, but it is now using a new trusted certificate."

    index = log_data.find(search_str)
    print index

    return

if __name__ == '__main__':
    main()

How do I extract the IP address? Your response is appreciated.

like image 913
Santhosh Avatar asked Jan 16 '26 22:01

Santhosh


1 Answers

Really simple answer:

msg = "IP 1.2.3.4 is currently trusted in the white list, but it is now using a new trusted certificate."

parts = msg.split(' ', 2)

print parts[1]

results in:

1.2.3.4

You could also do REs if you wanted, but for something this simple...

like image 175
AlG Avatar answered Jan 19 '26 13:01

AlG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!