'How do I log text and a variable in the same line in Python?
I am relativly new to coding with Python.
I recently set up a gps logging device with a raspberry pi and I want to make my log file look cleaner.
My current code for logging is:
logging.info('Altitude:')
logging.info(gpsd.fix.altitude)
It logs:
INFO:root:Altitude:
INFO:root:80
What I want to see in the log is:
Altitude: 80
I tried to do this with my limited knowledge with python, but it only resulted in failure.
Thanks! Also, any other tips for cleaning up the log file?
Solution 1:[1]
Try:
logging.info('Altitude:%s' % gpsd.fix.altitude)
Solution 2:[2]
If altitude is a decimal then
logging.info('Altitude: %d' % gpsd.fix.altitude)
will do it, there are several other ways to achieve the same thing though as I'm sure others can present!
Solution 3:[3]
logging.info('{}:{}'.format("Altitude", gpsd.fix.altitude)
You can use format method. Have a look at the examples to understand format better.
Example:
print '{}:{}'.format("Altitude", 80)
Output
Altitude:80
Solution 4:[4]
In Python >=3.6 you can do this :
logging.info(f"Altitude: {gpsd.fix.altitude}")
By adding the "f" at the beginning of the string the value between brackets will be interpreted as a variable and will be replaced by its value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Owen |
| Solution 3 | thefourtheye |
| Solution 4 | leas |
