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

Bar*_*rry 2 python python-3.x

我有两个变量,总共存储两个数字。我想将这些数字组合在一起,并用逗号分隔。我读到可以使用{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)

Dee*_*ace 5

您使事情变得过于复杂。

由于只有介于两者之间{并且}将要评估的内容,因此您只需

print(f'the number is {x},{y}') 对于第一个示例,以及

print(f'the email is {x}@{y}{z}') 第二。