Reputation: 161
so I have the line:
text="Temp :" + TempVar + "C CPUTemp: " + CPUTempVar + "C"
How would I get that to work as a string on text?
Upvotes: 0
Views: 485
Reputation: 22473
I endorse @Cyber's answer (the format
method) as the straightforward, modern Python way to format strings.
For completeness, however, the old way (common prior to Python 2.6) was a string interpolation operator:
text = 'Temp : %dC CPUTemp: %dC' % (TempVar,CPUTempVar)
It still works in the latest Python 3 releases, and will commonly be seen in older code.
Or you could use my say package to do inline string substitution (or printing) similar to what you'd expect from Ruby, Perl, PHP, etc.:
from say import *
text = fmt('Temp : {TempVar}C CPUTemp: {CPUTempVar}C')
Upvotes: 1
Reputation: 180471
You need to cast as strings if you want to concat non strings to strings:
TempVar = 100
CPUTempVar = 100
text="Temp: " + str(TempVar) + "C CPUTemp: " + str(CPUTempVar) + "C"
print(text)
Temp: 100C CPUTemp: 100C
Upvotes: 0
Reputation: 117926
You can use format
to create a string from your variables.
TempVar = 100
CPUTempVar = 50
text = 'Temp : {}C CPUTemp: {}C'.format(TempVar,CPUTempVar)
>>> text
'Temp : 100C CPUTemp: 50C'
Upvotes: 3