Reputation: 169
I have wrote the following code to split a line, what I was trying to do is to get the 1.802e+05 and 1.739e+04. I think I can split the line with space, then I can get those values, but what I got so far is only the letter H. Anyone can show me where my bug is?
line = 'Htin 1.802e+05 [J kg^-1] Htout 1.739e+04 [J kg^-1]'
line.split(' ')
print line[0]
Upvotes: 2
Views: 651
Reputation: 881635
Personally, I'd skip the split
and go right for a re
solution -- e.g if every number you want to extract is in exponential notation,
numstrings = re.findall(r'\d\.\d+e[+-]\d+', line)
would work. Just adjust the RE pattern to the forms of numbers you want to extract!
Upvotes: 2
Reputation: 3464
line.split()
will return a result which you are not storing anywhere. Using line[0]
will give you the character at index 0
in the string line
.
This should be more what you want:
>>> line = 'Htin 1.802e+05 [J kg^-1] Htout 1.739e+04 [J kg^-1]'
>>> lines = line.split()
>>> lines
['Htin', '1.802e+05', '[J', 'kg^-1]', 'Htout', '1.739e+04', '[J', 'kg^-1]']
>>> lines[1]
'1.802e+05'
>>> lines[5]
'1.739e+04'
Upvotes: 1
Reputation: 103834
You can use try/except:
>>> line = 'Htin 1.802e+05 [J kg^-1] Htout 1.739e+04 [J kg^-1]'
>>> result=[]
>>> for e in line.split():
... try:
... result.append(float(e))
... except ValueError:
... pass
...
>>> result
[180200.0, 17390.0]
Upvotes: 1
Reputation: 4035
import re
line = 'Htin 1.802e+05 [J kg^-1] Htout 1.739e+04 [J kg^-1]'
a=line.split()
for x in a:
if re.findall("[0-9][0-9]",x):
print (x)
Output:
>>>
1.802e+05
1.739e+04
>>>
re
module for search what you want.
Upvotes: 0
Reputation: 49803
Split doesn't alter line; it returns a list of strings. But even if it did, line[0] wouldn't give you one of the numbers.
Upvotes: 1
Reputation: 49
line.split()
return the result, which you haven't stored anywhere. So, that line has no effect.
In the next line, line
is still the string, so line[0] is H
line = 'Htin 1.802e+05 [J kg^-1] Htout 1.739e+04 [J kg^-1]'
temp = line.split(' ')
print temp[0]
Upvotes: 2