Avoiding Type Errors with the str() Function

Avoiding Type Errors with the str() Function

Often, you’ll want to use a variable’s value within a message. For example, say you want to wish someone a happy birthday. You might write code like this:

birthday.py age = 23
message = "Happy " + age + "rd Birthday!"
print(message)

You might expect this code to print the simple birthday greeting, Happy 23rd birthday! But if you run this code, you’ll see that it generates an error:

Traceback (most recent call last):

File "birthday.py", line 2, in <module>
message = "Happy " + age + "rd Birthday!"
u TypeError: Can't convert 'int' object to str implicitly

This is a type error. It means Python can’t recognize the kind of information you’re using. In this example Python sees at u that you’re using a variable that has an integer value (int), but it’s not sure how to interpret that value.

Python knows that the variable could represent either the numerical value 23 or the characters 2 and 3. When you use integers within strings like this, you need to specify explicitly that you want Python to use the integer as a string of characters. You can do this by wrapping the variable in the str() function, which tells Python to represent non-string values as strings:

age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)

Python now knows that you want to convert the numerical value 23 to a string and display the characters 2 and 3 as part of the birthday message. Now you get the message you were expecting, without any errors:

Happy 23rd Birthday!

Working with numbers in Python is straightforward most of the time. If you’re getting unexpected results, check whether Python is interpreting your numbers the way you want it to, either as a numerical value or as a string value.

READ  Festive Discount Offer Inside - Entity Framework Tutorial by Packt Publishing

Integers in Python 2

Python 2 returns a slightly different result when you divide two integers:

>>> python2.7
>>> 3 / 2
1

Instead of 1.5, Python returns 1. Division of integers in Python 2 results in an integer with the remainder truncated. Note that the result is not a rounded integer; the remainder is simply omitted. To avoid this behavior in Python 2, make sure that at least one of the numbers is a float. By doing so, the result will be a float as well:

>>> 3 / 2
1
>>> 3.0 / 2
1.5
>>> 3 / 2.0
1.5
>>> 3.0 / 2.0
1.5

This division behavior is a common source of confusion when people who are used to Python 3 start using Python 2, or vice versa. If you use or create code that mixes integers and floats, watch out for irregular behavior.

This article is an excerpt from A Hands-On, Project-Based Introduction to Programming by Eric Matthes

Reproduced with permission from No Starch Press

Leave a Reply

Your email address will not be published.