Parse variable into variables >Re: Apology
Jason Orendorff
jason at jorendorff.com
Sun Feb 24 21:34:33 EST 2002
Timothy Rue wrote:
> I can read a line from a file but then I want to parse the line into a set
> of variables. How do I do the parse?
Use regular expressions!
A nice Python introduction:
http://py-howto.sourceforge.net/regex/regex.html
Here is some sample code that parses a line of user input.
# -------------------------------------------------
import re
print "Please type a number, then a word. Like this:"
print "> 1884384 toad"
print
x = raw_input('> ')
match = re.match(r'^\s*(\d+)\s+(\w+)\s*$', x)
if match is None:
print "Sorry, I couldn't parse that."
else:
number, word = match.groups()
print "Your number was:", number
print "Your word was:", word
## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list