josh
josh

Reputation: 1205

Python: Log multiple strings to one line

Title says it all, I need to log two strings in one line.
For example, something like this:

logging.info(string1,string2)

Thank you :)

Upvotes: 5

Views: 16073

Answers (5)

Sida Zhou
Sida Zhou

Reputation: 3705

Using f strings, you could turn this into a one-liner and make it quite readable.

# python3 f-strings
logging.info(f'{string1} {string2}')

Upvotes: 2

Mingyu
Mingyu

Reputation: 33359

logger.info("String 1: {0!r} --- String 2: {1!r}".format(string1, string2))

Demo:

>>> print "String 1: {0!r} --- String 2: {1!r}".format('hello', 'world')
String 1: 'hello' --- String 2: 'world'
>>> print "String 1: {1!r} --- String 2: {0!r}".format('world', 'hello')
String 1: 'hello' --- String 2: 'world'

Two things to note here:

  1. The number in {0!r} and {1!r} specify the argument you get from input.
  2. '!s' (apply str()) and '!r' (apply repr()) can be used to convert the value before it is formatted.

Upvotes: 0

Patt Mehta
Patt Mehta

Reputation: 4204

>>> ( s1,s2 ) = ( 'apple','mango' );
>>> print( '{},{}'.format(s1,s2) );
apple,mango

Upvotes: 2

Blender
Blender

Reputation: 298166

The logging functions act like this:

result = arg1 % (arg2, arg3, ...)

What you have will try to format the first string with the second string:

result = string1 % string2

Either manually specify a formatting string:

logging.info('%s %s', string1, string2)

Or join them together into one string:

logging.info(' '.join([string1, string2]))

Upvotes: 17

David Wolever
David Wolever

Reputation: 154494

You can use %-formatting, like this:

logging.info("%s %s", string1, string2)

For example:

 >>> string1, string2 = "spam", "pie"
 >>> logging.info("%s %s", string1, string2)
 INFO: spam pie

Upvotes: 3

Related Questions