Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...