0

I am retrieving data by reading multi line python string.

My string is shown below:

Hostname: windos
Model: OS_5000
OS: 18.2
OS Kernel 64-bit  [2020_Stable]
....
.....
....

I am looking to extract Model value i.e. 5000 from this string. Not sure how to do it.

 dpath = op.response()
                    dpath = dpath[dpath.find("Model:")+ 6 : dpath[dpath.find("Model:")+ 11]

Also, model string could be of variable length. Is there any better way of doing it?

EDIT: Model value could be numeric or non-numeric.

3
  • 1
    After you've found the start of the model number, find the first newline ("\n") after that position (str.find() takes an optional second parameter to specify the starting position to search). Use that position as the end of your slice. Commented Jun 25, 2020 at 19:47
  • We need to know what assumptions we can make about string that are safe. Commented Jun 25, 2020 at 19:48
  • We need to extract till end of line. Commented Jun 25, 2020 at 19:50

3 Answers 3

1

You should try with a regular expression:

import re

re.search('Model: (.*)', dpath).group(1)
Sign up to request clarification or add additional context in comments.

Comments

1

Try : (using Regex)

import re
s = """Hostname: windos
Model: 5000
OS: 18.2
OS Kernel 64-bit  [2020_Stable]"""
match = re.search('Model: (\d+)', s)
if match:
    print(match.group(1))

5000

If multiple Model in the string:

import re
s = """Hostname: windos
Model: 5000
OS: 18.2
Model: 12343434
OS Kernel 64-bit  [2020_Stable]"""
match = re.findall('Model: (\d+)', s)
if match:
    print(match)

['5000', '12343434']

Comments

1

Use regular expression:

import re
model = re.findall('model\:\s*(\d+)', dpath, re.I)
if model:
    model = model[0]

Here I use "re.I" to search case insensitive word "model" "\s*" — means if there will be some space after the colon or not it won't break this script. So it find numbers in next cases: Model: 5000 Model:5000 model: 5000 model: 5000

3 Comments

Thanks: But model could be non numeric as well. How to cover this case?
use \w+ then in place of \d+
@Ammad very simple: 'model\:\s*(\S+)' '\S' – means non space symbol

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.