Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

python - How to print the value that must be formatted to width of binary value of n

def print_formatted(number):
    for i in range(1,number+1):
        a=oct(i)
        b=hex(i)
        c=bin(i)
        d=a.replace("0o","")
        e=b.replace("0x","")
        f=c.replace("0b","")
        print(i,end=" ")
        print(d,end=" ")
        print(e,end=" ")
        print(f)

if __name__ == '__main__':
    n = int(input())
    print_formatted(n)

I have written this code but i dont have idea how to apply format function in this code to get the desired result

question from:https://stackoverflow.com/questions/65880040/how-to-print-the-value-that-must-be-formatted-to-width-of-binary-value-of-n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not sure exactly what you wanted, but I think this might be it?

def print_formatted(number):
    fstr = '{{:{}d}} {{:>{}}} {{:>{}}} {{:>{}}}'.format(len(str(number+1)),len(oct(number+1)),len(hex(number+1)),len(bin(number+1)))
    for i in range(1,number+1):
        a=oct(i)
        b=hex(i)
        c=bin(i)
        d=a.replace("0o","")
        e=b.replace("0x","")
        f=c.replace("0b","")
        print(fstr.format(i, d, e, f))

if __name__ == '__main__':
    n = int(input())
    print_formatted(n)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...