728x90
728x90

print 문 출력 문자에 색깔 넣는 방법 (ANSI Escape Code)

들어가며

  • 파이썬(Python)에서 @print@ 문으로 특정 문자를 출력할 때, 색깔을 넣는 방법을 정리해본다.

 

ANSI Escape Code

개념

  • 텍스트를 출력할 때, 색상, 스타일기타 속성을 제어하는 데 사용되는 특수한 제어 문자열
  • 주로 터미널 또는 콘솔에서 출력되는 텍스트에 다양한 효과를 주기 위해 사용된다.
  • 이 코드는 @\033@ (혹은 @\x1b@)로 시작하며, 뒤에 @[@와 특정 @색상 코드@ 또는 @스타일 코드@가 포함된다. 그리고 마지막에는 @m@으로 끝나는 형태로 이루어져 있다.
\033[<색상코드>m <텍스트> \033[0m     # 방법1
\x1b[<색상코드>m <텍스트> \x1b[0m     # 방법2

 

@\033@ / @\x1b@ : 이스케이프 문자(Escape Character)

@[@ : CSI (Control Sequence Introducer)

@<code>@ : 적용할 속성이나 색상

@m@ : 코드가 끝났음을 의미

 

방법

  • 다음과 같이 ANSI Escape Code를 이용하여 출력문에 색깔을 넣을 수 있다.
\033[<색상코드>m <텍스트> \033[0m

 

예제 코드 1
# ANSI 이스케이프 코드
## 시작 : \033[<색상코드>m 
## 끝 : \033[0m

COLOR_RED = "\033[31m"
COLOR_GREEN = "\033[32m"
COLOR_YELLOW = "\033[33m"
COLOR_BLUE = "\033[34m"
COLOR_END = "\033[0m"

# 테스트
print(f"""
{COLOR_RED}RED{COLOR_END}
{COLOR_GREEN}GREEN{COLOR_END}
{COLOR_YELLOW}YELLOW{COLOR_END}
{COLOR_BLUE}BLUE{COLOR_END}
""")

 

예제 코드 2 : <색상코드>에 따른 모든 색깔 확인 해보기
def print_color():
    for i in range(11):
        for j in range(10):
            n = 10 * i + j
            if n > 108:
                break
            print(f"\033[{n}m {n:3d}\033[m", end=' ')
        print()

print_color()

 

참고 사이트

 

ANSI escape code - Wikipedia

From Wikipedia, the free encyclopedia Method used for display options on video text terminals ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling, and other options on video text terminals and terminal

en.wikipedia.org

 

728x90
728x90