Menu

Casting

Casting Data Structures

Casting works on one value at a time. The functions str(), int(), float() and bool() each take a single value and return a converted copy of it, and none of them converts the items inside a list, array or record one by one. A structured data type therefore has each element cast separately, wherever that element is used.

Converting a whole structure

If you pass a list to str(), Python converts the container's own printed form. That form keeps the punctuation that shows the structure: square brackets around the items, quotation marks around any text and commas between the items. A shopping list of three items becomes one long string such as ['bread', 'milk', 'eggs'], with brackets and quotes mixed in among the words. That is not the clean comma-separated data line a file needs, and a program reading it back would treat the brackets and quotes as part of the data.

The same is true in the other direction. int() expects one valid number string or number, so handing it a whole list or record makes the program fail rather than converting the items inside.

Casting each element instead

Suppose a swimming club stores three race times as text: "31", "28" and "35". To add them up, cast each one with int() at the moment you use it, so each conversion acts on a single element. The total can then be turned back into text with str() so that it can be joined to a label.

Data heldCasting the whole structureCasting each element
Three prices stored as text: "2.50", "1.20" and "3.00"str() keeps the brackets and quotation marks, giving one messy stringfloat() on each price gives 2.5, 1.2 and 3.0, which can be added
A record holding a name and a scoreThe cast keeps the field names and the punctuation around themstr() on the score alone, so it can be joined to text

A quick check: if the value you hand to a cast holds more than one item, you are converting the container, not its contents.

Practise this