user2926908
user2926908

Reputation: 73

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?

Upvotes: 7

Views: 17442

Answers (4)

leas
leas

Reputation: 379

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.

Upvotes: 10

dawg
dawg

Reputation: 104102

Try:

logging.info('Altitude:%s' % gpsd.fix.altitude)

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239693

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

Upvotes: 4

Owen
Owen

Reputation: 1736

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!

Upvotes: 5

Related Questions