Python Part I · Module 2 · Variables and Data Types
Converting Between Text and Numbers
The previous chapter gave you a way to discover that a value is text when you needed a number. This one is about what to do next. Python provides a small set of conversions you can request explicitly — text to whole number, text to decimal, anything to text — and the important word is explicitly, because Python never does this for you behind your back. That refusal is deliberate and it is the behaviour you want. The chapter also covers the case that separates a script that works from one that survives: a conversion that cannot succeed, because the text genuinely is not a number. That happens constantly with real data, and knowing that it fails loudly rather than quietly is the point.
Foundation10 min readPythonPart IFundamentalsConversionParsing
Part I · Module 2 · Chapter 2.11 · Converting Between Text and Numbers
1. The Problem, Concretely
A script reads a line from a report and ends up with this:
seed_text = "4210"
print(type(seed_text))<class 'str'>It looks like a number. It is text. Chapter 2.9 §3 explained why: everything read from outside arrives as text.
To use it as a number, you have to ask for a number.
2. Text to Whole Number
seed_text = "4210"
seed = int(seed_text)
print(seed)
print(type(seed))4210
<class 'int'>int is a name Python provides, used like print and type: name, brackets, the value to convert. It gives back a new value of type int.
Note carefully: seed_text was not changed. It still refers to the text "4210". The conversion produced a separate value, which the name seed now refers to. That is the name/value model from Chapter 2.2 behaving exactly as described.
3. Text to Decimal
slack_text = "-0.043"
slack = float(slack_text)
print(slack)
print(type(slack))-0.043
<class 'float'>float does the same job for numbers with a fractional part. Use it when the value could have one — measured quantities, timing numbers, percentages.
int and float are not interchangeable:
print(float("4210"))4210.0float("4210") succeeds and gives 4210.0 — a float holding a whole quantity, which Chapter 2.6 §2 covered.
4. Anything to Text
The reverse direction:
seed = 4210
seed_text = str(seed)
print(seed_text)
print(type(seed_text))4210
<class 'str'>str converts a value into its text form. This is what you need when writing a number into a file name, a report line or a message.
It works on every type in this module:
print(str(182.4))
print(str(True))
print(str(None))182.4
True
NoneNote the last two: str(True) produces the text "True", and str(None) produces the text "None" — which is precisely the "True"-is-not-True distinction from Chapters 2.8 and 2.9, now created deliberately rather than by accident.
5. Nothing Is Automatic
Worth stating plainly, because some languages do convert silently and Python does not.
Python will never decide on your behalf that a piece of text should be treated as a number. If you want a number, you ask. If you do not ask, the value stays text and behaves as text.
This feels stricter at first and is the behaviour you want. A language that silently converts is a language where a typo in a report becomes a wrong number instead of an error.
6. When Conversion Fails
Here is the case that matters.
value = int("n/a")ValueError: invalid literal for int() with base 10: 'n/a'Python could not turn "n/a" into a whole number, so it stopped and said so. The message even quotes the offending text back at you, which is exactly what you need when a report has one bad row in four hundred.
This is not a rare situation. Real data contains n/a, -, TBD, blank fields and column headers, and a script that reads a report will meet all of them.
Some near-misses also fail:
print(int("4.5"))ValueError: invalid literal for int() with base 10: '4.5'int() on text wants a whole number, and "4.5" is not one. Use float("4.5") instead, which works.
7. Surrounding Spaces Are Tolerated
One small convenience worth knowing, since real data is untidy:
print(int(" 4210 "))4210int() ignores spaces around the number. It does not ignore anything else — int("42 10") still fails.
8. Converting to a Boolean
bool() exists, and it has one behaviour that traps people badly enough to be worth showing.
print(bool("False"))TrueThat is not a mistake. bool() applied to text does not read the word — it asks whether there is any text at all. "False" has five characters, so it is True. So is "no", "0" and "anything".
The only text that converts to False is empty text:
print(bool(""))False9. Predict, Run, Observe
Predict each — including which ones fail and with what error.
print(int("100"))
print(float("100"))
print(str(100))
print(int(" 7 "))
print(bool(""))
print(bool("False"))
print(int("seven"))100
100.0
100
7
False
True
ValueError: invalid literal for int() with base 10: 'seven'The last line stops the file, so nothing after it would run — Chapter 1.4 §4, a run-time failure that happens part-way through. Everything above it printed first.
10. Exercise
Exercise 1 — round trip. Start with the text "4210". Convert it to a whole number, print it and its type. Then convert that back to text, print it and its type. Confirm you end where you started.
Exercise 2 — choose the conversion. For each piece of text from a report, say which conversion you would use and why: (a) "600" (number of tests); (b) "182.44" (runtime); (c) "-0.043" (slack); (d) "PASS" (status).
(For (d): none. It is a status word and should stay text.)
Exercise 3 — predict three failures. Predict the error for each, then run them one at a time:
int("4.5")
int("")
int("n/a")All three raise the same kind of error. Read each message and say which part changes.
Exercise 4 — the bool trap. Predict the output, then run it:
print(bool("True"))
print(bool("False"))
print(bool(""))Then answer: if a report column contains the word False, what would bool() tell you, and why is that dangerous?
11. Summary
int(),float()andstr()convert explicitly. Name, brackets, value — likeprintandtype.- Conversion produces a new value. The original name still refers to the original value.
- Python never converts silently. If you want a number from text, you ask; otherwise it stays text.
int()on text wants a whole number —"4.5"fails,float("4.5")succeeds.- Failure raises
ValueErrorand stops the script, quoting the offending text. Loud failure beats a plausible wrong number. - Surrounding spaces are tolerated; anything else is not.
bool()on text asks only whether there is any text.bool("False")isTrue. Never use it to interpret a word.- Reacting to a failed conversion is Module 14. Knowing that it fails is enough for now.
You can now find out what a value is and change it into what you need. The next chapter steps back and asks what it means that a name can refer to one type on one line and a different type on the next.
Where this fits
Part of the Python curriculum.
