Simon Elms
Simon Elms

Reputation: 19808

Is it possible to format text input so Python recognises it as a list?

I've got a console application that prompts the user to enter various inputs. Works fine.

Now I'd like to add some additional parameters to the function that is called to allow the user to filter the results. In particular, I'd like the user to be able to enter a date range, to return all records created in that time period.

I could add two separate parameters to the function, such as lowerDateLimit and upperDateLimit. But it seems neater to me to accept a pair of values as a tuple: dateLimits, which would be of the form: (lowerDateLimit, upperDateLimit).

Is there any way for a user entering text in a console to be able to format their input so that Python would recognise it as a list or a tuple?

Or would the more Pythonic thing to do be to just use two separate parameters for the lower and upper date limits?

Upvotes: 0

Views: 129

Answers (3)

tlm2021
tlm2021

Reputation: 33

I can't comment yet, but you if need a list instead of a tuple, ast.literal_eval can handle that by including the brackets:

In [1]: import ast

In [2]: ast.literal_eval('[1,2,3]')
Out[2]: [1, 2, 3]

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

>>> ast.literal_eval(raw_input('Foo: '))
Foo: 1,2,3
(1, 2, 3)

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 114035

In [84]: nums = [int(i) for i in raw_input("Enter space separated integers: ").split()]
Enter space separated integers: 1 5 6 7 3 56  2 3 4 2 1

In [85]: nums
Out[85]: [1, 5, 6, 7, 3, 56, 2, 3, 4, 2, 1]

Upvotes: 2

Related Questions