Python 3.6风格f-strings字面量字符串插值。
项目描述
使用f-strings(PEP 498)风格的字面量字符串插值,无需Python 3.6。
用法
访问全局和局部变量。
import os import fmt as f g_foo = 'global-foo' g_bar = 'global-bar' g_num = 23 g_ls = [1, 2, 3] def scope(): l_foo = 'local-foo' l_bar = 'local-bar' print( f('{l_foo}, {l_bar}') ) # 'local-foo, local-bar' print( f('{g_foo}, {g_bar!r}') ) # "global-foo, 'global-bar'" scope() print( f('{{ }}') ) # '{ }' print( f('hex: {g_num:#x}') ) # '0x17' print( f('{os.EX_OK}') ) # '0' print( f('{g_ls[0]}, {g_ls[1]}, {g_ls[2]}') ) # '1, 2, 3'
注意: 闭包会有些棘手,必须将外部作用域变量作为参数传递给f,以便在闭包内部添加引用,从而使其工作。
import fmt as f def outer(x='xx'): y = 'yy' def inner(): print( f('{x}, {y}', x, y) ) # "xx, yy" return inner outer()()
表达式评估。
from datetime import datetime import fmt as f class S(object): def __str__(self): return 'hello' def __repr__(self): return 'hi' def __format__(self, fmt): return 'abcdefg'[int(fmt)] print( f('{1234567890:,}') ) # '1,234,567,890' print( f('{1 + 2}') ) # '3' print( f('{str(1 + 2)!r}') ) # "'3'" print( f('{[i for i in range(5)]}') ) # '[0, 1, 2, 3, 4]' ls = range(5) print( f('{{i for i in ls}}') ) # 'set([0, 1, 2, 3, 4])' or '{0, 1, 2, 3, 4}' print( f('{{k:v for k,v in zip(range(3), range(3, 6))}}') ) # '{0: 3, 1: 4, 2: 5}' print( f('{datetime(1994, 11, 6):%Y-%m-%d}') ) # '1994-11-06' print( f('{list(map(lambda x: x+1, range(3)))}') ) # '[1, 2, 3]' print( f('{S()!s}, {S()!r}, {S():1}') ) # 'hello, hi, b'
此外,您还可以为方便起见注册一些命名空间。
import fmt as f f.mregister({'x': 1, 'y': 2}) # register multiple f.register('z', 3) # register only one def func(x, y): return x + y print( f('{func(x, y)}') ) # '3' print( f('{func(x, z)}') ) # '4' print( f('{func(y, z)}') ) # '5'
注意: locals()可能覆盖globals(),globals()可能覆盖您注册的命名空间。
安装
通过pip安装
[sudo] pip install fmt -U
许可证
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。
源分布
fmt-0.3.1.tar.gz (5.9 kB 查看散列值)
构建发行版
fmt-0.3.1-py2.py3-none-any.whl (8.1 kB 查看散列值)
关闭
fmt-0.3.1.tar.gz 的散列值
算法 | 散列摘要 | |
---|---|---|
SHA256 | 7665aa8cf3258d16557a20e4f657434d274d9d0e1755259a7a064c18875cbfa3 |
|
MD5 | c574f596f417e938427d74f950a9555e |
|
BLAKE2b-256 | 45ab4f3a1184fe37a288df89bc609882256a47a663190683d70a477b35c90b2d |
关闭
fmt-0.3.1-py2.py3-none-any.whl 的散列值
算法 | 散列摘要 | |
---|---|---|
SHA256 | ea6658900a51b12d8c9e0fe118279c6904daba6e77596e6aed7e8851461c8e33 |
|
MD5 | dec69e083f1a2938a93fc60f92394efe |
|
BLAKE2b-256 | 77056b4e068e35400b137a9d59fcf8d0f482693259f6e2c4f0ee967ee86f6e68 |