fruit
fruit

Reputation: 135

parsing a line of text to get a specific number

I have a line of text in the form " some spaces variable = 7 = '0x07' some more data"

I want to parse it and get the number 7 from "some variable = 7". How can this be done in python?

Upvotes: 0

Views: 246

Answers (3)

Nick T
Nick T

Reputation: 26717

Basic regex code snippet to find numbers in a string.

>>> import re
>>> input = " some spaces variable = 7 = '0x07' some more data"
>>> nums = re.findall("[0-9]*", input)
>>> nums = [i for i in nums if i]  # remove empty strings
>>> nums
['7', '0', '07']

Check out the documentation and How-To on python.org.

Upvotes: 0

hlfrk414
hlfrk414

Reputation: 151

I would use a simpler solution, avoiding regular expressions.

Split on '=' and get the value at the position you expect

text = 'some spaces variable = 7 = ...'
if '=' in text:
    chunks = text.split('=')
    assignedval = chunks[1]#second value, 7
    print 'assigned value is', assignedval
else:
    print 'no assignment in line'

Upvotes: 4

Uri
Uri

Reputation: 89749

Use a regular expression.

Essentially, you create an expression that goes something like "variable = (\d+)", do a match, and then take the first group, which will give you the string 7. You can then convert it to an int.

Read the tutorial in the link above.

Upvotes: 2

Related Questions