Prepare > Python > Strings > String Formatting

2023. 7. 12. 21:50HackerRank-Python

 

String Formatting | HackerRank

Print the formatted decimal, octal, hexadecimal, and binary values for $n$ integers.

www.hackerrank.com

 

문제


The four values must be printed on a single line in the order specified above for each i from  to N. 
Each value should be space-padded to match the width of the binary value of N  and the values should be separated by a single space.

 

=> 4개의 값은 각 i에서 N까지 위에 지정된 순서대로 한 줄에 인쇄되어야 합니다.각 값은 N의 이진 값 너비와 일치하도록 공백으로 채워야 하며 값은 단일 공백으로 구분되어야 합니다.

 

단일공백이 무슨 뜻인지 모르겠음.

 

 

 

 

코드


def print_formatted(number):
    for i in range(1, number+1):
    # your code goes here

        print(
            str(i).rjust(len(bin(number)[2:])) ,
            oct(i)[2:].rjust(len(bin(number)[2:])) ,
            hex(i)[2:].upper().rjust(len(bin(number)[2:])) ,
            bin(i)[2:].rjust(len(bin(number)[2:])) ,
        )

        

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

 

 

 

 

노트


oct(i): i(정수)를 8진수로 변경하는 함수

hex(i): i(정수)를 16진수로 변경하는 함수

bin(i): i(정수)를 2진수로 변경하는 함수

 

 

another code

def print_formatted(number):
    space = len(f"{number:b}")
    for n in range(1,number+1):
        print( f"{n:>{space}d} {n:>{space}o} {n:>{space}X} {n:>{space}b}")
    

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

 

 

 

참조


 

python]hackerRank] String Formatting 진수변환, 간격(저장용)

def print_formatted(number): # your code goes here if __name__ == '__main__': n = int(input()) print_formatted(n) 기본 코드가 주어지고 정수 N dmf하나 입력받아 10진수, 8진수, 16진수, 2진수로 정수 N 까지 출력을 하는 건데

3catpapa.tistory.com

 

[Python] 진법 변환 총 정리?!

[Pyhton 진법 변환] n진수 → 10진수 python에서는 기본적으로 int() 라는 함수를 지원합니다. int(string, base) 위와 같은 형식으로 사용하면 됩니다. base에는 진법을 넣으면 됩니다. print(int('111',2)) print(int

security-nanglam.tistory.com