Reputation: 139
I'm using a list comprehension to get a list of numerical values that are separated by a semicolon, ;
, within a string.
I need to get a 0 from missing values on either side of the semicolon.
Example string without missing values:
job_from_serial_st = 'xxxxx\rxxxxxx\rxxxx\rGAX=77.00;85.00\rxxxxx\r'
Using my list comprehension I would get the following list of values: [7700, 8500]
But how can I get a list of values from strings like 'GAX=77.00;\r'
or 'GAX=;85.00\r'
?
I'm expecting to get the following lists from the example strings with missing values:
[7700, 0]
or [0, 8500]
def get_term(A, B, phrase):
n = A.len()
start = phrase.find(A) + n
end = phrase.find(B, start)
term = phrase[start:end]
return term
# GET GAX NUMBER
gax_nums = get_term(r'GAX=', r'\r\x1e\x1d', job_from_serial_st)
gax = [int(float(x) * 100) for x in gax_nums.split(';')]
print(gax)
Upvotes: 1
Views: 959
Reputation: 15120
You can add a condition to the list comprehension to return 0 if there is no number before or after the semicolon (also replaced your function with a series of splits to retrieve the numbers from the string).
s = 'xxxxx\rxxxxxx\rxxxx\rGAX=77.00;\rxxxxx\r'
nums = s.split('GAX=')[1].split('\r')[0].split(';')
gax = [int(float(n) * 100) if n else 0 for n in nums]
print(gax)
# [7700, 0]
Upvotes: 1