在python中的字符串内插入变量
我是python新手,我想知道如何将变量放入字符串中,以便在LCD 20x4显示器(2004A)中显示此类变量的内容 我的代码如下所示:在python中的字符串内插入变量,python,string,variables,Python,String,Variables,我是python新手,我想知道如何将变量放入字符串中,以便在LCD 20x4显示器(2004A)中显示此类变量的内容 我的代码如下所示: with open("temperature.txt") as myfile: currenttemp=myfile.readlines() lcd_string("%(currenttemp)" ,LCD_LINE_1,2) 不幸的是,这将在LCD显示屏中打印“%(currenttemp)”,而不是currenttemp变量值。Python中的字符串格式
with open("temperature.txt") as myfile:
currenttemp=myfile.readlines()
lcd_string("%(currenttemp)" ,LCD_LINE_1,2)
不幸的是,这将在LCD显示屏中打印
“%(currenttemp)”
,而不是currenttemp变量值。Python中的字符串格式示例:
代码:
a = "one line file"
print("this file contains: %s" %a)
this file contains: one line file
输出:
a = "one line file"
print("this file contains: %s" %a)
this file contains: one line file
有关各种字符串格式化技术的性能比较,请参见此处:。特别是查看。另外,您现在使用的
readlines
将是文件中的行列表。因此,您还需要确保您的currenttemp
实际上是什么。currenttemp始终是一个单行文件,所以这不会是一个问题。谢谢@但它仍然会在列表中。因此,如果您的文件中只有“foo”,那么通过使用readlines
您将拥有['foo']
。如果你把它按原样放在一个字符串中,你最终会打印出['foo']
。您可能需要查看read()
,如果文件末尾有新行,则可能需要查看使用strip
删除任何不需要的空白,然后:currenttemp=myfile.readlines()[0][:-1]否则:currenttemp=myfile.readlines()[0]