When types collide
Python refuses. You can't glue a string and an integer together directly — they're different types and Python won't guess what you meant.
Why Python is strict about this
Consider what "adding" a string and a number could mean:
Python doesn't know. Rather than guess wrong and silently produce bad output, it stops and tells you there's a problem. That's a feature, not a bug.
The fix: str()
Convert the number to a string first, then concatenate:
str() turns any value into its string equivalent. The number 25 becomes the text "25", and now Python can glue it together with the rest.
The other direction: int() and float()
You can also go the other way — convert a string into a number:
And for decimals:
What happens when the conversion fails
If the string doesn't look like a number, Python raises an error:
You can only convert strings that actually contain valid numbers. "25" works. "twenty-five" does not.
Key takeaways
- Python will not mix strings and numbers automatically — you have to convert explicitly
str()turns a number into a string so you can concatenate itint()andfloat()turn strings into numbers so you can do math- If the string doesn't contain a valid number, the conversion will fail with a
ValueError
No comments yet. Add the first comment to start the discussion.