10진수를 16진수의 문자열로 변환하는 방법을 소개합니다.
1. hex()를 이용한 방법
hex(integer)
는 integer의 16진수를 문자열로 리턴합니다.
int = 255
hex = hex(int)
print(hex)
print(type(hex))
Output:
0xff
<class 'str'>
문자열 앞의 0x
를 제거하고 숫자만 남기고 싶다면 아래와 같이 lstrip()
을 이용할 수 있습니다.
int = 255
hex = hex(int)
hex = hex.lstrip("0x")
print(hex)
Output:
ff
2. format()을 이용한 방법
format(intger, format_spec)
으로 10진수를 16진수 문자열로 변환할 수 있습니다.
format_spec
은 아래 4가지가 될 수 있으며, 형식에 따라서 prefix 0x
의 차이가 있고, 대소문자의 차이가 있습니다.
#x
: 0xff#X
: 0XFFx
: ffX
: 0xFF
int = 255
hex = format(int, '#x')
print(hex)
hex = format(int, '#X')
print(hex)
hex = format(int, 'x')
print(hex)
hex = format(int, 'X')
print(hex)
Output:
0xff
0XFF
ff
FF
3. f-string을 이용한 방법
format()
과 동일하게 f-string
을 이용하여 동일하게 문자열로 변환할 수 있습니다.
int = 255
hex = f'{int:#x}'
print(hex)
hex = f'{int:#X}'
print(hex)
hex = f'{int:x}'
print(hex)
hex = f'{int:X}'
print(hex)
Output:
0xff
0XFF
ff
FF
Loading script...
Related Posts
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제
- Python - count(), len() 함수
- Python - join() 함수, 문자열 합치기
- Python - 줄바꿈 입력 방법
- Python - 딕셔너리를 JSON으로 변환
- Python - JSON을 딕셔너리로 변환
- Python - 딕셔너리 Index로 접근/순회 방법
- Python - 딕셔너 리 CSV 파일 쓰기/읽기
- Python - 딕셔너리 update() 함수
- Python - JSON 예쁘게(pretty), 정렬하여 출력
- Python - CSV 파일을 JSON 파일로 변환
- Python - CSV 파일을 리스트로 변환
- Python - List를 Set로 변환
- Python - Set을 List로 변환
- Python - 텍스트 파일 이어서 쓰기
- Python - 파일 끝 찾기
- Python - 파일 수정 시간, 생성 시간 확인