相关疑难解决方法(0)

嵌套的f字符串

感谢David Beazley的推文,我最近发现新的Python 3.6 f字符串也可以嵌套:

>>> price = 478.23
>>> f"{f'${price:0.2f}':*>20s}"
'*************$478.23'
Run Code Online (Sandbox Code Playgroud)

要么:

>>> x = 42
>>> f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-'''
'-*+.42.+*-'
Run Code Online (Sandbox Code Playgroud)

虽然我很惊讶这是可能的,但我很遗憾这是多么实际,何时嵌套f字符串是有用的?这可以涵盖哪些用例?

注意:PEP本身没有提到嵌套f字符串,但是有一个特定的测试用例.

python string-formatting python-3.x python-3.6 f-string

44
推荐指数
6
解决办法
8765
查看次数

使用f字符串在@处插入字符或符号

我有两个变量,总共存储两个数字。我想将这些数字组合在一起,并用逗号分隔。我读到可以使用{variablename:+}插入加号或空格或零,但是逗号不起作用。

x = 42
y = 73
print(f'the number is {x:}{y:,}')
Run Code Online (Sandbox Code Playgroud)

这是我的怪异解决方案,即时通讯添加+,然后用逗号替换+。有没有更直接的方法?

x = 42
y = 73
print(f'the number is {x:}{y:+}'.replace("+", ","))
Run Code Online (Sandbox Code Playgroud)

可以说我有名称和域名,我想建立一个电子邮件地址列表。因此,我想将两个名称在Middel中的@符号和结尾的.com融合。

那只是我可以想到的一个例子。

x = "John"
y = "gmail"
z = ".com"
print(f'the email is {x}{y:+}{z}'.replace(",", "@"))
Run Code Online (Sandbox Code Playgroud)

结果是:

print(f'the email is {x}{y:+}{z}'.replace(",", "@"))
ValueError: Sign not allowed in string format specifier
Run Code Online (Sandbox Code Playgroud)

python python-3.x

2
推荐指数
1
解决办法
286
查看次数