Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log text and a variable in the same line in Python?

Tags:

python

logging

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?

like image 300
user2926908 Avatar asked Jul 13 '26 07:07

user2926908


1 Answers

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.

like image 93
leas Avatar answered Jul 14 '26 19:07

leas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!