[파이썬] 문자열의 문자 유니코드 변환

파이썬에서는 문자열을 다루는 많은 기능들이 제공됩니다. 그 중에서도 문자열의 각 문자를 유니코드로 변환하는 방법을 알아보겠습니다.

방법 1: ord() 함수 사용하기

ord() 함수는 문자의 유니코드를 반환해주는 내장 함수입니다. 다음은 이 함수를 사용하여 문자열의 각 문자를 유니코드로 변환하는 예시입니다:

text = "Hello, World!"

for char in text:
    unicode_value = ord(char)
    print(f"The unicode value of '{char}' is {unicode_value}")

위 코드의 실행 결과는 다음과 같습니다:

The unicode value of 'H' is 72
The unicode value of 'e' is 101
The unicode value of 'l' is 108
The unicode value of 'l' is 108
The unicode value of 'o' is 111
The unicode value of ',' is 44
The unicode value of ' ' is 32
The unicode value of 'W' is 87
The unicode value of 'o' is 111
The unicode value of 'r' is 114
The unicode value of 'l' is 108
The unicode value of 'd' is 100
The unicode value of '!' is 33

방법 2: unicodedata 모듈 사용하기

unicodedata 모듈은 파이썬에서 유니코드 문자에 대한 정보를 제공하는 모듈입니다. unicodedata.name() 함수를 사용하여 문자의 이름을 가져올 수도 있습니다. 다음은 unicodedata 모듈을 사용하여 문자열의 각 문자의 유니코드와 이름을 출력하는 예시입니다:

import unicodedata

text = "안녕하세요"
for char in text:
    unicode_value = ord(char)
    char_name = unicodedata.name(char)
    print(f"The unicode value of '{char}' is {unicode_value} ({char_name})")

위 코드의 실행 결과는 다음과 같습니다:

The unicode value of '안' is 50504 (HANGUL SYLLABLE AN)
The unicode value of '녕' is 47484 (HANGUL SYLLABLE NYEONG)
The unicode value of '하' is 54620 (HANGUL SYLLABLE HA)
The unicode value of '세' is 50612 (HANGUL SYLLABLE SE)
The unicode value of '요' is 46300 (HANGUL SYLLABLE YO)

위의 두 가지 방법을 사용하여 문자열의 각 문자를 유니코드로 변환하는 방법에 대해 알아보았습니다. 이러한 변환은 유니코드에 기반한 작업을 할 때 유용하게 사용될 수 있습니다.