简体   繁体   中英

find something in a string then print it in python

im sure this is simple but im not good with regexp or string manipulation and i want to learn :)

I have an output from a string I get using snimpy. it looks like this:

ARRIS DOCSIS 3.0 Touchstone WideBand Cable Modem <<HW_REV: 1; VENDOR: Arris Interactive, L.L.C.; BOOTR: 1.2.1.62; SW_REV: 7.3.123; MODEL: CM820A>>

I want to be able to look into that string and use that info in an if to then print some stuff. I want to see if the model is a CM820A and then check the firmware version SW_REV and if its not the right version I want to print the version else I move on to the next string i get from my loop.
host.sysDescr it what returns the above string. as of now I know how to find all the CM820A but then i get sloppy when I try to verify the firmware version.

sysdesc = host.sysDescr
if "CM820A" in str(sysdesc):        
    if "7.5.125" not in str(sysdesc):
        print("Modem CM820A " + modem + " at version " + version)
        print(" Sysdesc = " + sysdesc)
    if "7.5.125" in sysdesc:
        print ("Modem CM820A " + modem + " up to date")

Right now I am able to see if the CM820A has the right version easily but I can't print only the version of the bad modems. I was only able to print the whole string which contains a lot of useless info. I just want to print form that string the SW_REV value.

Question

I need help with how to do this then I will understand better and be able to rewrite this whole thing which I currently am using only to learn python but I want to put to practice for useful purposes.

All you need is split() , you can split your string with a special character for example see the following :

>>> l= s.split(';')
['ARRIS DOCSIS 3.0 Touchstone WideBand Cable Modem <<HW_REV: 1', ' VENDOR: Arris Interactive, L.L.C.', ' BOOTR: 1.2.1.62', ' SW_REV: 7.3.123', ' MODEL: CM820A>>']

>>> for i in l :
...  if 'BOOTR' in i:
...   print i.split(':')
... 
[' BOOTR', ' 1.2.1.62']

So then you can get the second element easily with indexing !

This answer will simply explain how to retrieve your desired information. You will need to perform multiple splits on your data.

First, I notice that your string's information is subdivided by semi-colons. so:

description_list = sysdesc.split(";")

will create a list of your major sections. since the sysdesc string has a standard format, you can then access the proper substring:

sub_string = description_list[3]

now, split the substring with the colon:

revision_list = sub_string.split(":")

now, just reference:

revision_list[1]

whenever you want to print it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM