Saturday, April 7, 2012

Python: How to find the integer and float in a string

Reference: http://stackoverflow.com/a/10059001/1276534
Credits: MellowFellow, hexparrot

If you have a string from somewhere, say a textbook, or an input. The string contain the data information you need. How do you extract the string? There are quite a few way to do it, range from hard code accessing it from index, to finding the E=, to using regular expression. In this example we will go over the middle of the range one. Because as beginner, it might not be the best idea to introduce regular expression yet. Plus this is the version I understand, maybe the regular expression version will be provided soon. (If you can't wait, you can check out from the reference link from above, there is the regular expression solution as well.)
# Assume you get this string from either a file or input from user
text_string = 'The voltage is E=500V and the current is I=6.5A'

# The starting index of this locating the voltage pattern
voltage_begin = text_string.find('E=')
# The ending index, note we are ending at 'V'
voltage_end = text_string.find('V', voltage_begin)

voltage_string = text_string[voltage_begin:voltage_end]
print(voltage_string, 'is at index:', voltage_begin, voltage_end)

#Since we know about the first to index is not useful to us
voltage_string = text_string[voltage_begin+2:voltage_end]

# So since now we have the exact string we want, we can cast it to an integer
voltage_as_int = int(voltage_string)
print(voltage_as_int)

No comments:

Post a Comment