如何使用f“"打印二进制数字.字符串而不是.format()? [英] How to print binary numbers using f"" string instead of .format()?

查看:47
本文介绍了如何使用f“"打印二进制数字.字符串而不是.format()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要将某些数字打印为二进制格式,我们只需使用 .format()方法,如下所示:

For printing some numbers to their binary formats, we simply use the .format() method, like so:

# Binary
for i in range(5+1):
    print("{0:>2} in binary is {0:>08b}".format(i))

0 in binary is 00000000
1 in binary is 00000001
2 in binary is 00000010
3 in binary is 00000011
4 in binary is 00000100
5 in binary is 00000101

类似的格式用于其他格式(十六进制和八进制)的打印,只需要将后者的花括号替换为我们要打印的数字即可.但是,是否可以使用新的 f" 字符串替换 .format()命令?我知道这看似微不足道,但我在试用新功能时遇到了麻烦,除了 f" 可使代码更短且更具可读性.

Similar is for printing in other formats (hex and octal) which just requires replacing the latter braces to the digits we want to print. But is there a way to use the new f"" string to replace the .format() command? I know this might seem trivial but I stumped over this while playing around with the new feature, besides f"" makes the code shorter and more readable.

for i in range(5+1):
    print(f'{0:>2} in binary is {0:>08b}')
# This prints out just 0s

推荐答案

您的f字符串中应该包含表达式而不是索引:

Your f-string should have expressions in it rather than indices:

f'{i:>2} in binary is {i:>08b}'

任何在原始格式字符串中具有 0 的地方都应替换为实际的第一个参数:在这种情况下为 i .

Anywhere you had 0 in the original format string should be replaced by the actual first argument: in this case i.

注意事项

f字符串中的表达式被评估两次,但是 format 的参数在您通过索引访问它时仅被评估一次.这对于更复杂的表达式很重要.例如:

The expression in the f-string is evaluated twice, but the argument to format is only evaluated once when you access it by index. This matters for more complicated expressions. For example:

"{0:>2} in binary is {0:>08b}".format(i + 10)

在这里,加法 i + 10 仅发生一次.另一方面

Here the addition i + 10 only happens once. On the other hand

f"{i+10:>2} in binary is {i+10:>08b}"

进行两次加法,因为它等同于

does the addition twice because it is equivalent to

"{:>2} in binary is {:>08b}".format(i + 10, i + 10)

"{0:>2} in binary is {1:>08b}".format(i + 10, i + 10)

解决方法是预先计算多次出现在您的f字符串中的表达式的结果:

The workaround is to pre-compute the results of expressions that appear in your f-string more than once:

j = i + 10
f"{j:>2} in binary is {j:>08b}"

现在 j 被多次评估,但这只是一个简单的参考.

Now j is evaluated multiple times, but it's just a simple reference.

这篇关于如何使用f“"打印二进制数字.字符串而不是.format()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆