2016-07-09 2 views
1

Ich bin neu in Python und ich frage mich, wie man eine Variable in eine Zeichenfolge einfügen, um den Inhalt einer solchen Variable in einem LCD 20x4 Display (2004A) anzuzeigen.Variable in String in Python einfügen

Der Code Ich habe sieht wie folgt aus:

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

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

Leider ist dies druckt "%(currenttemp)" in der LCD-Anzeige, und nicht der currenttemp Variablenwert.

+1

[Offizielle Dokumentation zu Strings] (https://docs.python.org/2/library/string.html). – Mephy

+0

Sehen Sie sich insbesondere [String-Formatierung] an (https://docs.python.org/3/library/string.html#format-string-syntax). Außerdem wird Ihr 'currenttemp' im Moment mit' readlines' eine Liste von Zeilen aus Ihrer Datei sein. Also, Sie wollen auch sicherstellen, was genau Sie wollen, dass Ihr 'currenttemp' tatsächlich ist. – idjaw

+0

currenttemp ist immer eine 1-zeilige Datei, das wäre also kein Problem. Vielen Dank! – Ramirous

Antwort

2

Ein Beispiel für Zeichenfolge in Python Formatierung:

Code:

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

Ausgang:

this file contains: one line file 

Für Performance-Vergleich von verschiedenen String-Technik Formatierung siehe hier: Python string formatting: % vs. .format