Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

String concatenation and types

Why doesn't Python catch different types when concatenating with commas as it does when using the plus sign?

>>> print("Today is", weather, "degrees.")
Today is 75 degrees.


>>> print("Today is " + weather + " degrees.")
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    print("Today is " + weather + " degrees.")
TypeError: Can't convert 'int' object to str implicitly

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Some languages like Java and JavaScript can do a type conversion implicitly when doing concatenation. Python isn't one of them. If you want to use concatenation to produce your string with the value of a variable that was previously holding a number you must convert the value to a string first. Alternatively, you can use string interpolation instead.

Hope this helps! :sparkles:

When you use the "+" you are attempting to perform a math function on multiple items, like the below code:

print("Hello" + WORLD)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'WORLD' is not defined

Since "Hello" is a string and WORLD is an int, you get an error because those two data types cannot be added together.

However, when you use a "," you are creating a Tuple (mutable list), like the below code:

print("Hello", "World")
('Hello', 'World')

Note: Notice how the print output is formatted when using the commas, versus how it would be formatted when using two strings with a plus sign (as shown below):

OR

As in your example above, you have a value of 75 set to the variable weather. When performing the print function, Python is "grabbing" the value set to the variable weather.

print("hello" + "WORLD")
helloWORLD

I hope this gives you some insight, feel free to open up a terminal window and play with these commands (print) in Python, it can help you see how the code behaves in realtime.