0

so I have the line:

text="Temp :" + TempVar + "C CPUTemp: " + CPUTempVar + "C"  

How would I get that to work as a string on text?

0

3 Answers 3

3

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'
Sign up to request clarification or add additional context in comments.

1 Comment

In Python 2.6 and earlier, you'll need indexes in the format string: 'Temp : {0}C CPUTemp: {1}C'.format(TempVar,CPUTempVar). I know 2.6 is a bit long in the tooth now, and later versions don't need that much specification, but I still see a good deal of it in use, so any code I distribute widely, I put the indices in.
1

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')

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.