用于执行延迟的F字符串计算的库。

fstr的Python项目详细描述


fstr

Build StatusPyPICode style: blackLicense: MIT

1在python 2中使用f-string语法:

importfstrx=1y=2template=fstr("{x} + {y} = {x + y}")print(template.evaluate())
1 + 2 = 3

2。在python 2和3中使用f-string语法而不是str.format

importfstrcommon_error_message=fstr("function {function.__name__!r} failed because {error}")defadd(x,y):try:returnx+yexceptExceptionase:msg=common_error_message.format(function=add,error=e)print(msg)defsub(x,y):try:returnx+yexceptExceptionase:msg=common_error_message.format(function=sub,error=e)print(msg)add(1,"2")sub("5",3)
function 'add' failed because unsupported operand type(s) for +: 'int' and 'str'
function 'sub' failed because can only concatenate str (not "int") to str

完全PEP-498符合性

python 2中f-string语法的其他向后兼容库只实现了pep的specification中定义的一些功能。对fstr的测试用例甚至从CPython's test suite中提升(有一些细微的变化)。

格式说明符

格式说明符可以包含计算表达式。

importfstrimportdecimalwidth=10precision=4value=decimal.Decimal('12.34567')fstr("result: {value:{width}.{precision}}").evaluate()
'result:      12.35'

一旦对格式说明符中的表达式求值(如有必要),格式说明符就不会被f-string求值器解释就像在str.format()中一样,它们仅仅被传递到正在格式化的对象的__format__()方法中

表达式中的lambdas

importfstrfstr("{(lambda x: x*2)(3)}").format()
'6'

错误处理

确切的消息将根据您是否使用Python<;3.6而有所不同


importfstrfstr("x={x")
File "fstr", line 1
  x={x
      ^
SyntaxError: Mismatched braces in f-string.

importfstrfstr("x={!x}")
File "fstr", line 1
  x={!x}
    ^
SyntaxError: Empty expresion not allowed.

性能考虑

fstr并不意味着要替代python的f-string语法。相反,它主要用作在 否则可能使用str.format的情况。另外,Python的f-string语法能够在编译时进行性能优化,而这些优化不是提供给str.formatfstr.format鉴于此,我们只比较fstr.formatstr.format

fstr的性能取决于您是否:

  • 是否使用python<;3.6。
  • 提前定义f-string模板。

例如,这将显著减慢

foriinrange(10):s=fstr("{i}**2 = {i**2}").format(i=i)

如果在循环外定义模板:

template=fstr("{i}**2 = {i**2}")foriinrange(10):s=template.format(i=i)

str.formatfstr.format

fromtimeitimporttimeitstr_setup="template = '{x}' * 10"fstr_setup="import fstr\ntemplate = fstr('{x}' * 10)"str_result=timeit("template.format(x=1)",setup=str_setup,number=1000000)fstr_result=timeit("template.format(x=1)",setup=fstr_setup,number=1000000)print("str.format() : %s seconds"%str_result)print("fstr.format() : %s seconds"%fstr_result)

Python<;3.6

str.format() : 0.741672992706 seconds
fstr.format() : 6.77992010117 seconds

Python=3.6

str.format: 0.7007193689933047 seconds
fstr.format: 0.9083925349987112 seconds

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何创建比较器   java将所有接口读入列表   java Android Studio在Webview中隐藏特定URL的操作栏   java如何在春季从云存储中生成URL文件而无需持续时间   icalendar如何使用Java以日历格式发送ics电子邮件附件?   如果textfield包含数字,则在运行时进行java检查   java util日志属性中何时需要“.level”?   java在一个字符串中显示json   跨平台日志系统的java Log4j替代方案   coldfusion在Lucee上安装Cassandra Java驱动程序   SpringWebMVC4Java配置不工作   windows使用java程序添加环境变量,并且能够在我从计算机打开“环境”选项卡时看到   java未设置变量和方法   mysql在java中通过查询更改数据库的现有行   java如何使用递归方法查找所有可能的数字   java如何使非原语类成员不可变   java将信息从输入按钮传递到标签