컴퓨터공학/기타 프로그래밍

[Python3] 큰 따옴표(")와 작은 따옴표(')

TaeGyeong Lee 2023. 3. 26. 21:51

큰 따옴표(Double Quotes)와 작은 따옴표(Single Quotes)

상황에 따라 추천하는 경우가 다를 뿐 차이가 없다고 보셔도 무방합니다.

문자열에 작은 따옴표가 포함되는 경우, 큰 따옴표로 문자열을 감싸 주어야 합니다.

example = "I'm an apple"

# 출력 결과 : I'm an apple

반대로 문자열에 큰 따옴표가 포함되는 경우, 작은 따옴표로 문자열을 감싸 주어야 합니다.

example = 'Apple said "Hello banana"'

# 출력 결과 : Apple said "Hello banana"

문자열에 둘 다 들어가야 하는 경우, 큰 따옴표/작은 따옴표 세개로 문자열을 감싸 주어야 합니다.

example = """"Hello Apple?" banana said. "I'm banana"."""

# 출력 결과 : "Hello Apple?" banana said. "I'm banana".

C언어 등 전통적인 언어와 같은 방식으로도 표현할 수 있습니다.

example = "How do you do? Apple said. \"I\'m find bro\" banana said"

# 출력 결과 : How do you do? Apple said. "I'm find bro" banana said

다양한 방법이 있으나 프로그래밍을 함에 있어 그 방식을 통일하는 것이 좋을 것 같습니다. 저는 마지막 방법을 추천드립니다.

- 출처 : https://docs.python.org/ko/3/tutorial/introduction.html#strings

 

큰/작은 따옴표가 동일하다는 근거

아래 코드는 파이썬 tokenizer 파일의 일부입니다. 해당 로직에 따라 파이썬 프로그램을 해석하게 되는데, 보시다시피 큰 따옴표와 작은 따옴표로 시작하는 경우를 동일한 조건문을 통해 해석하고 있습니다.

...
letter_quote:
    /* String */
    if (c == '\'' || c == '"') {
        int quote = c;
        int quote_size = 1;             /* 1 or 3 */
        int end_quote_size = 0;

        /* Nodes of type STRING, especially multi line strings
           must be handled differently in order to get both
           the starting line number and the column offset right.
           (cf. issue 16806) */
        tok->first_lineno = tok->lineno;
        tok->multi_line_start = tok->line_start;
...