1

I'm new to python and I was wondering how to put a variable inside a string to show the contents of such variable in an LCD 20x4 display (2004A).

The code I have looks as follows:

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

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

Unfortunately, this prints "%(currenttemp)" in the LCD display, and not the currenttemp variable value.

Ramirous
  • 149
  • 2
  • 12
  • 1
    [Official documentation on strings](https://docs.python.org/2/library/string.html). – Mephy Jul 09 '16 at 01:14
  • In particular look at [string formatting](https://docs.python.org/3/library/string.html#format-string-syntax). Also, your `currenttemp` right now by using `readlines` is going to be a list of lines from your file. So, you also want to make sure what exactly it is you want your `currenttemp` to actually be. – idjaw Jul 09 '16 at 01:16
  • currenttemp is always a 1 line file, so that wouldn't be a problem. Thanks! – Ramirous Jul 09 '16 at 01:20
  • @Ramirous It would still be in a list. So if you had just 'foo' in your file, by using `readlines` you will have `['foo']`. And if you then put it in a string as is you will end up printing `['foo']`. You might want to look at `read()` and possibly look at removing any unwanted white space using `strip` – idjaw Jul 09 '16 at 01:25
  • If the file has new line in the end then: currenttemp=myfile.readlines()[0][:-1] otherwise: currenttemp=myfile.readlines()[0] – arshovon Jul 09 '16 at 01:33
  • @arsho That wouldn't take care of any leading whitespace and you don't know how much whitespace there is in the file surrounding the text you want on that one line. `read().strip()` would work best. With your method you are always assuming that you have a single whitespace character at the end of the line. That isn't a good assumption to always make. – idjaw Jul 09 '16 at 01:34

1 Answers1

2

An example of string formatting in Python:

Code:

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

Output:

this file contains: one line file

For performance comparison of various string formatting technique see here: Python string formatting: % vs. .format

Community
  • 1
  • 1
arshovon
  • 13,270
  • 9
  • 51
  • 69