What is the difference between str(x) and "", x, ""

example exercise https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-101/modules/cspath-python-functions/projects/physics-class

I have been using commas to concatenate but the hint advises me to use str()

Example:
I use

print("The GE train does", train_work, "Joules of work over", train_distance, "meters")

instead of

print("The GE train does " + str(train_work), "Joules of work over " + str(train_distance), "meters")

Both return the same output but I have to write a lot more in the 2nd option. Is using commas bad?

Hello @micro6373093900, welcome to the forums! When you use commas, you’re actually creating (and then printing) what’s effectively a tuple. Because of the way you’re printing it, it doesn’t appear any different, but if you wanted to use concatenation elsewhere (not inside a print() function), you’d have to use str() on any non-string values and +:

a = ("a", "b", "c")
print(a)
#>>("a", "b", "c")
b = "a" + "b" + "c"
print(b)
#>>"abc"

I hope that helps!

3 Likes