1

I have a BME280 environment sensor that returns a tuple in a variable called envi.

envi = bme.values
print(envi)

returns all three values of temp, pressure and humidity.

If I print(envi[1]) I get a string returned for pressure such as '1029.23hPa'

As this returned value needs calibrating ever so slightly, I simply need to add 3 to it, before publishing it via MQTT to Adafruit via...

c.publish(conf['user']+"/feeds/pres", env[1])

What would be the correct syntax to add 3 to env[1] please? Is there a way I can do this?

John
  • 99
  • 1
  • 1
  • 10
  • See [here](https://stackoverflow.com/questions/1038824/how-do-i-remove-a-substring-from-the-end-of-a-string-in-python) and [here](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int-in-python). – mkrieger1 Feb 23 '19 at 21:27
  • Not sure why you marked me as -1 for lack of research when I spent a fair amount of time researching how to convert a string to integer, getting various errors along the way. I even posted elsewhere on other forums where I didn't get a solution, so decided to post here. Doesn't enthuse me. – John Feb 23 '19 at 21:36

2 Answers2

1

Do you want to do this ?

# Python 3.6+
envi[1] = f"{float(envi[1].strip('hPa')) + 3:.2f}hPa"

# Python pre 3.6
envi[1] = "{:.2f}hPa".format(float(envi[1].strip('hPa')) + 3)
Fukiyel
  • 1,166
  • 7
  • 19
  • What is your Python version ? I updated my response, if your version is older than Py 3.6, it's normal, use the second line instead – Fukiyel Feb 23 '19 at 21:13
  • I am testing this on both a Raspberry Pi and Mac. The actual code is running on a flashed ESP8266 with micropython. The version of Python on the Pi was 2.7 something... I need to change the default Python to be v3.6+. When I changed the code, I received another error... 'tuple object doesn't support item assignment' but I simply substituted envi[1] for a new variable and added that to the MQTT line. This works perfectly, thanks,. – John Feb 23 '19 at 21:24
0

You can use:

s = '1029.23hPa'

f'{float(s[:-3]) + 3}hPa'
# 1032.23hPa

or

f"{float(s.rstrip('hPa')) + 3}hPa"
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73