简体   繁体   English

替代在Python 3.5+中传递格式字符串作为关键字参数

[英]Alternative to passing a format string as keyword argument in Python 3.5+

In Python 3.5, using keyword arguments in str.format has been deprecated: 在Python 3.5中,不推荐在str.format使用关键字参数:

"Hi {s}".format(s="world")

From the string docs : string文档

Deprecated since version 3.5 : Passing a format string as keyword argument format_string has been deprecated. 从版本3.5开始不推荐使用:不推荐使用格式字符串作为关键字参数format_string

What are the best alternatives in Python 3.5+? Python 3.5+中最好的替代品是什么?

Deprecation is about string.Formatter and not about str.Formatter : 弃用是关于string.Formatter而不是关于str.Formatter

Source: 资源:

Passing a format string as keyword argument format_string to the format() method of the string.Formatter class has been deprecated. 将格式字符串作为关键字参数format_string传递给string.Formatter类的format()方法已被弃用。

You can use in str.format , but not in string.Formatter 您可以在str.format中使用,但不能在string.Formatter

Or use fstrings : 或者使用fstrings

name = "Bob"
hello = f"Hello {name}"
print (hello)

Output: 输出:

Hello Bob

Try this 尝试这个

name = "john"
hello = "GoodMorning %s" %(name,)
print (hello)

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

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