[Tutor] How to get two user inputs in same prompt seperated by a special character?
Alan Gauld
alan.gauld at btinternet.com
Mon Jul 16 11:51:25 CEST 2012
On 14/07/12 04:46, Santosh Kumar wrote:
> height_in_feet = input("How much feet are you long: ")
> remaining_inches = input("How much inches remained? ")
>
> Here I want something like:
> Enter you height in format like 5' 10"
Mario has given a partial answer for this specific case although he
missed stripping of the inches symbol " at the end.
However in the general case what you want to do is quite hard (and
the reason most UIs ask for separate values) You need to parse the
character string input identifying any markers (like ' and ") and
extract the values. There are several ways to do this:
1) use split() based on the markers, works well for simple cases,
less so for symbols like lbs, ft, etc
2) read the characters in one by one and process them using a state
machine. Works well for simple cases with multiple char markers (or
multiple variations of the same (like ' or ft or feet) and for formal
specification of input format (typically where the input is normally a
file and exceptionally a human).
3) use regular expressions to extract recognised patterns, works better
for unstructured input.
3) use a formal parser to extract the values, most powerful but usually
most work too.
But it is generally easier (for the programmer) and safer (better
data quality) to ask for each value explicitly.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list