简体   繁体   English

如何单独打印二进制数字的数字 Python?

[英]How do I print a binary number's digits individually Python?

I am trying to understand how to print off a binary numbers digits individually.我想了解如何单独打印二进制数字。 For example, if the binary number is 1011, I want to print to the console:例如,如果二进制数是 1011,我想打印到控制台:

1 1

0 0

1 1

1 1

I am basically going to assign these numbers individually to different GPIO pins of a Pi.我基本上会将这些数字分别分配给 Pi 的不同 GPIO 引脚。

How about this one:这个怎么样:

number = str(1011)
for i in number:
    print(i)

try this:尝试这个:

bin=str(1011)
def print_to_console(agg, item):
  print(f'{item}\n')

reduce(print_to_console, bin, bin[0])

Assuming you are storing binary number in variable, its as simple as this假设您将二进制数存储在变量中,就这么简单

a = 11000
for i in str(a):
    print(i)

Output: Output:

1
1
0
0
0

but if wont print the left most zeros, ie if num is 00100, the above code will print 1,0 and 0. To not lose left most zeros, store binary digit as a string.但如果不打印最左边的零,即如果 num 为 00100,则上面的代码将打印 1,0 和 0。为了不丢失最左边的零,将二进制数字存储为字符串。

a = "0100"
for i in a:
    print(i)

Output: Output:

0
1
0
0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM