【问题标题】:Insert variable inside string in python [duplicate]在python中的字符串内插入变量[重复]
【发布时间】:2016-11-11 15:37:38
【问题描述】:

我是 python 新手,我想知道如何将变量放入字符串中以在 LCD 20x4 显示器 (2004A) 中显示此类变量的内容。

我的代码如下:

with open("temperature.txt") as myfile:
currenttemp=myfile.readlines()

lcd_string("%(currenttemp)" ,LCD_LINE_1,2)

不幸的是,这会在 LCD 显示屏上打印"%(currenttemp)",而不是当前温度变量值。

【问题讨论】:

  • 特别看string formatting。此外,您现在使用readlines 的currenttemp 将成为您文件中的行列表。因此,您还需要确定您想要的 currenttemp 到底是什么。
  • currenttemp 始终是一个 1 行文件,所以这不是问题。谢谢!
  • @Ramirous 它仍然在列表中。因此,如果您的文件中只有“foo”,通过使用readlines,您将拥有['foo']。如果你把它放在一个字符串中,你最终会打印['foo']。您可能想查看 read() 并可能查看使用 strip 删除任何不需要的空白区域
  • 如果文件末尾有新行则:currenttemp=myfile.readlines()[0][:-1] 否则:currenttemp=myfile.readlines()[0]

标签: python string variables


【解决方案1】:

Python 中的字符串格式化示例:

代码:

a = "one line file"
print("this file contains: %s" %a)

输出:

this file contains: one line file

各种字符串格式化技术的性能比较见这里:Python string formatting: % vs. .format

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 1970-01-01
    • 2019-06-19
    • 2011-03-22
    • 1970-01-01
    • 2017-09-08
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多