简体   繁体   English

Python:将多个字符串记录到一行

[英]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 :)谢谢 :)

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]))

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
>>> ( s1,s2 ) = ( 'apple','mango' );
>>> print( '{},{}'.format(s1,s2) );
apple,mango

Using f strings, you could turn this into a one-liner and make it quite readable.使用 f 字符串,您可以将其转换为单行并使其更具可读性。

# python3 f-strings
logging.info(f'{string1} {string2}')
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. {0!r} 和 {1!r} 中的数字指定您从输入中获得的参数。
  2. '!s' (apply str()) and '!r' (apply repr()) can be used to convert the value before it is formatted. '!s' (apply str()) 和 '!r' (apply repr()) 可用于在格式化之前转换值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM