使用f字符串插入字符或符号@。

3

我有两个变量,分别存储两个数字的值。我希望将这些数字组合起来,并用逗号分隔。我了解到可以使用{variablename:+}来插入加号、空格或零,但逗号无效。

x = 42
y = 73
print(f'the number is {x:}{y:,}')

这是我的奇怪解决方案,我添加了一个 + 然后将其替换为逗号。是否有更直接的方法?

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

假设我拥有姓名和域名,并且想要构建一个电子邮件地址列表。因此,我希望将这两个名称融合在一起,中间用@符号,最后以.com结尾。

这只是我能够想到的一个例子。

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

导致结果如下:

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

3
这句话的意思是“这个数是{x},{y}”。 - jonrsharpe
2个回答

5

您正在使事情过于复杂。

由于只有在 {} 之间的内容才会被计算,因此您可以简单地执行以下操作:

对于第一个示例,执行print(f'the number is {x},{y}');对于第二个示例,执行print(f'the email is {x}@{y}{z}')


4

当你把东西放在 f 格式字符串的 "{}" 中时,它实际上正在被计算。因此,任何不应该放在外部 "{}" 中的内容都不应该放进去。

一些例子:

x = 42
y = 73
print(f'Numbers are: {x}, {y}') # will print: 'Numbers are: 42, 73'
print(f'Sum of numbers: {x+y}') # will print: 'Sum of numbers: 115'

你甚至可以做类似于这样的事情:

def compose_email(user_name, domain):
      return f'{user_name}@{domain}'

user_name = 'user'
domain = 'gmail.com'
print(f'email is: {compose_email(user_name, domain)}')

>>email is: user@gmail.com

更多示例请参见: 嵌套f字符串

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接