Reputation: 684
Suppose
p1="python"
p2="script"
r=0.242424
print(p1+" "+p2+" "+r) #wrong or error in python
print(p1+" "+p2+" "+str(r)) #correct
Why do I we have to convert a float to string explicitly in Python, but other languages like Java convert it implicitly?
Upvotes: 0
Views: 124
Reputation: 395285
If you want to join various data types into a string, concatenation with +
or with the str.join
method will require them to be strings before you do it.
As Martijn shows, it's not needed for printing, but that can be confusing because printing by default includes newlines and a space that separates elements separated by commas that are being printed.
If you want to implicitly convert them to strings, I recomend the string.format
method:
>>> '{0} {1} {2}'.format(p1, p2, r)
'python script 0.242424'
This is quite a useful and efficient way to format text and not have to worry about the types, so long as you don't mind getting their default string representation.
Upvotes: 0
Reputation: 1123052
You don't. You only need to convert it explicitly when concatenating. print()
will use spaces to separate arguments on its own, converting each to a string:
print(p1, p2, r)
Quoting the print()
documentation:
All non-keyword arguments are converted to strings like
str()
does and written to the stream, separated by sep and followed by end.
sep defaults to the ' '
string.
You usually use string formatting to interpolate values into a string:
print("Running a {} {} to show the value of r={:.6f}".format(p1, p2, r))
Otherwise, trying to concatenate strings with other values does not convert values implicitly; this goes against the Zen of Python:
Explicit is better than implicit.
Upvotes: 3