python - 如何在二进制转换程序中的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 循环以及我能想到的几乎所有东西。我只是想知道我将如何做到这一点。任何帮助将不胜感激,我只是迷路了。
解决方案
尝试这样做:
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
推荐阅读
- r - R公式中y~1,y~0和y~-1有什么区别?
- javascript - TypeORM:创建/更新/删除多个多对一关系的最有效方法?
- tensorflow - 如何使用 LSTM 预测来自同一时间序列的新变量?
- powershell - 用于禁用 GPO 的计算机或用户部分的 Powershell 脚本
- php - 使用php从字符串中获取文件名
- android-studio - 离子电容器没有为安卓模拟器生成运行配置
- android - Android 如何通过 Retrifit 2 向服务器发送空值
- python - 将 Gerrit 触发器与附加阶段相结合
- autodesk-forge - forge properties.sqlite vs viewable json for revit 类型参数
- html - css - 根据父母数量的奇偶性选择每个元素(CSS或Less但没有JS)