liveBook · Manning

Data conversion

As explained in Python How-To

Data conversion is the transformation of a value or data from one type, format, or representation to another, explicitly or implicitly.

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

How Python How-To covers it

How deep it goes
Explains numeric constructors, conversion errors, container evaluation, and manual parsing, while deferring exception handling details.
Examples
Uses age input, numeric strings, string representations of lists, tuples, and dictionaries, and comma-separated integer parsing.
What it assumes
Starts from strings such as input values and teaches conversion into numeric and container data.
What you can do after
Apply int, float, eval, or manual parsing to retrieve values represented by strings, while handling conversion failures and untrusted data carefully.
How it connects
Connects strings with type casting, iterables, exception handling, eval, and parsing.

Also explained in

Compare how 21 books explain data conversion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.