首页 > 解决方案 > 如何在二进制转换程序中的python中每4位之后创建一个空格

问题描述

import collections
from collections import Counter
d = int(input('Pick a number to convert to Binary: '))

def convert(n, Counter = 0):
    Counter = 0
    if n > 1:
        convert(n//2)
    print(n % 2, end = '')
    
    
print("Your number in Binary is")
convert(d)

我不知道如何在输出中每 4 位或每 4 个数字创建一个空格。我尝试使用计数器 a for 循环以及我能想到的几乎所有东西。我只是想知道我将如何做到这一点。任何帮助将不胜感激,我只是迷路了。

标签: pythonbinary

解决方案


尝试这样做:

def convert(n, counter = None):
    if not counter:
        counter = 0
    counter += 1
    if n > 1:
        convert(n//2, counter)
    if counter % 4 == 0:
        print(" ", end="")
    print(n % 2, end = '')
    
    
    
print("Your number in Binary is")
convert(d)
print("")

输出 3456 作为输入:

Your number in Binary is
 1101 1000 0000

推荐阅读