Python 2.6 引入了该str.format()
方法,其语法与现有%
运算符略有不同。哪个更好,在什么情况下?
Python 3.6 现在通过语法f"my string"
. 此格式选项是否比其他格式更好?
下面使用每种方法,结果都一样,那么有什么区别呢?
#!/usr/bin/python sub1 = "python string!" sub2 = "an arg" sub_a = "i am a %s" % sub1 sub_b = "i am a {0}".format(sub1) sub_c = f"i am a {sub1}" arg_a = "with %(kwarg)s!" % {'kwarg':sub2} arg_b = "with {kwarg}!".format(kwarg=sub2) arg_c = f"with {sub2}!" print(sub_a) # "i am a python string!" print(sub_b) # "i am a python string!" print(sub_c) # "i am a python string!" print(arg_a) # "with an arg!" print(arg_b) # "with an arg!" print(arg_c) # "with an arg!"
此外,字符串格式化何时出现在 Python 中?例如,如果我的日志记录级别设置为 HIGH,我仍然会因为执行以下
%
操作而受到打击吗?如果是这样,有没有办法避免这种情况?log.debug("some debug info: %s" % some_info)