How can textual input become usable Python data? Values returned by input are strings, even when they represent numbers. Convert them before comparisons or calculations: a string age cannot be compared directly with the integer 18. section 2.2
Choose a conversion that matches the represented value:
- Use int("123") or float("3.25") to create numeric values. If the string is invalid, conversion raises ValueError; handle that possibility with try...except. section 2.2.2
- For strings representing lists, tuples, or dictionaries, list() and tuple() treat the string as an iterable of characters—not as the represented container. eval() evaluates the string as Python code, but use it only with trusted data. For untrusted input, parse the data yourself or consider ast. section 2.2.3 section 2.2.4
Listing 2.4 Casting numbers from strings
def cast_number(number_str):
try:
casted_number = float(number_str)
except ValueError:
print(f"Couldn't cast {repr(number_str)} to a number") #1
else:
print(f"Casting {repr(number_str)} to {casted_number}")
# Use the above function in a console
>>> cast_number("1.5")
Casting '1.5' to 1.5
>>> cast_number("2.3a")
Couldn't cast '2.3a' to a number
This example catches ValueError so an invalid numeric string does not halt the program. section 2.2.2
assert eval(numbers_list_str) == [1, 2]
assert eval(numbers_tuple_str) == (1, 2)
assert eval(numbers_dict_str) == {1: 'one', 2: 'two'}
These assertions show eval retrieving list, tuple, and dictionary values represented by strings. section 2.2.3
When the expected format is simple and known, parsing it directly is another option: remove the brackets from a comma-separated list string, split its contents, and convert each item with int(). section 2.2.3




















