字符串连接中的 Python 内联条件

标签 python conditional-expressions

我有这个:

msg = time + b' - ' + Logger.LEVELS_WORD[msg_loglevel] + b': ' + msg.encode('utf-8') + b'\n'

因为有时 msg 已经是字节,我想连接 msg.encode('utf-8') 如果它是字符串或者只是 msg,所以我这样做了:

msg = time + b' - ' + Logger.LEVELS_WORD[msg_loglevel] + b': ' + msg if isinstance(msg, bytes) else msg.encode('utf-8') + b'\n'

但它没有像我预期的那样工作,因为现在 msg 等于 msg。 (时间 + 日志级别未添加)。

我应该改用 if/else 吗?

最佳答案

条件表达式有一个 very low precedence ;它仅在 lambda 之前最后执行。因此,表达式在 time + b' - ' + Logger.LEVELS_WORD[msg_loglevel] + b': ' + msgmsg.encode('utf-8 ')) + b'\n'.

将条件表达式与 ifelse 分支放在括号中:

msg = time + b' - ' + Logger.LEVELS_WORD[msg_loglevel] + b': ' + (
    msg if isinstance(msg, bytes) else msg.encode('utf-8')) + b'\n'

考虑使用 duck-typing(测试 hasattr(msg, 'encode')),并将表达式分成多行以提高可读性。如果您使用的是 Python 3.5 或更新版本,也许您想使用 printf-style formatting :

if hasattr(msg, 'encode'):
    msg = msg.encode('utf-8')
msg = b'%s - %s: %s\n' % (time, Logger.LEVELS_WORD[msg_loglevel], msg)

关于字符串连接中的 Python 内联条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36795745/

相关文章:

python - 如果在 python 中赋值,则一行

java - 'Conditional expressions can be only boolean, not integral.' 是什么意思?

c - 条件表达式中的指针/整数类型不匹配

python - python中的prim算法

python - 如何对不同上下文的查询使用序列标签?

Matlab lsqcurvefit() 函数的 Python 等价性

if-statement - FLWOR 表达式不完整 : expecting 'return'

java - 在Java中,条件表达式是线程安全操作吗?

python - 如何定义只能调用一次的可调用对象?

python - Matplotlib imshow() 问题 : title on top of top xlabels, 和 ylabels 未在 pdf 中对齐