|
2 | 2 | <a id="strings"></a> |
3 | 3 | ### 3.10 Strings |
4 | 4 |
|
5 | | -매개변수가 모두 문자열인 경우에도 `format` 메소드나 `%` 연산자를 사용하여 포메팅하세요. |
6 | | -물론 `+` 나 `%` 를 언제 사용할지는 개발자의 판단에 따릅니다. |
7 | | - |
8 | | -```python |
9 | | -올바른 예시: x = a + b |
10 | | - x = '%s, %s!' % (imperative, expletive) |
11 | | - x = '{}, {}'.format(first, second) |
12 | | - x = 'name: %s; score: %d' % (name, n) |
13 | | - x = 'name: {}; score: {}'.format(name, n) |
14 | | - x = f'name: {name}; score: {n}' # Python 3.6+ |
15 | | -``` |
16 | | - |
17 | | -```python |
18 | | -잘못된 예시: x = '%s%s' % (a, b) # use + in this case |
| 5 | +- 매개변수가 모두 문자열인 경우에도 `format` 메소드나 `%` 연산자를 사용하여 포메팅하세요. |
| 6 | +- 물론 `+` 나 `%` 를 언제 사용할지는 개발자의 판단에 따릅니다. |
| 7 | + |
| 8 | + - 올바른 예 |
| 9 | + |
| 10 | + ```python |
| 11 | + x = a + b |
| 12 | + x = '%s, %s!' % (imperative, expletive) |
| 13 | + x = '{}, {}'.format(first, second) |
| 14 | + x = 'name: %s; score: %d' % (name, n) |
| 15 | + x = 'name: {}; score: {}'.format(name, n) |
| 16 | + x = f'name: {name}; score: {n}' # Python 3.6+ |
| 17 | + ``` |
| 18 | + |
| 19 | + - 부적절한 예 |
| 20 | + |
| 21 | + ```python |
| 22 | + x = '%s%s' % (a, b) # use + in this case |
19 | 23 | x = '{}{}'.format(a, b) # use + in this case |
20 | 24 | x = first + ', ' + second |
21 | 25 | x = 'name: ' + name + '; score: ' + str(n) |
22 | | -``` |
23 | | - |
24 | | -반목문에서 `+` 나 `+=` 연산자를 사용하여 문자열을 누적하는 행위는 삼가세요. |
25 | | -문자열은 변형이 불가하기 때문에 위와 같은 연산자를 사용하는 것은 불필요한 임시 오브젝트를 생성하게 되고 |
26 | | -결국 리니어한 실행시간이 아닌 제곱형태의 실행시간이 소요됩니다. |
27 | | -위의 연산자 대신 리스트에 문자열을 넣고 반복문이 종료되면 `''.join` 를 사용하는것이 더 바람직합니다. |
28 | | -(또는 각각의 문자열을 `io.BytesIO` 버퍼에 기록하는 것도 방법입니다.) |
29 | | - |
30 | | -```python |
31 | | -올바른 예시: items = ['<table>'] |
32 | | - for last_name, first_name in employee_list: |
33 | | - items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name)) |
34 | | - items.append('</table>') |
35 | | - employee_table = ''.join(items) |
36 | | -``` |
37 | | - |
38 | | -```python |
39 | | -잘못된 예시: employee_table = '<table>' |
| 26 | + ``` |
| 27 | + |
| 28 | +- 반목문에서 `+` 나 `+=` 연산자를 사용하여 문자열을 누적하는 행위는 삼가세요. |
| 29 | +- 문자열은 변형이 불가하기 때문에 위와 같은 연산자를 사용하는 것은 불필요한 임시 오브젝트를 생성하게 되고 결국 리니어한 실행시간이 아닌 제곱형태의 실행시간이 소요됩니다. |
| 30 | +- 위의 연산자 대신 리스트에 문자열을 넣고 반복문이 종료되면 `''.join` 를 사용하는것이 더 바람직합니다. (또는 각각의 문자열을 `io.BytesIO` 버퍼에 기록하는 것도 방법입니다.) |
| 31 | + |
| 32 | + - 올바른 예 |
| 33 | + |
| 34 | + ```python |
| 35 | + items = ['<table>'] |
| 36 | + for last_name, first_name in employee_list: |
| 37 | + items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name)) |
| 38 | + items.append('</table>') |
| 39 | + employee_table = ''.join(items) |
| 40 | + ``` |
| 41 | + |
| 42 | + - 부적절한 예 |
| 43 | + |
| 44 | + ```python |
| 45 | + employee_table = '<table>' |
40 | 46 | for last_name, first_name in employee_list: |
41 | 47 | employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name) |
42 | 48 | employee_table += '</table>' |
43 | | -``` |
44 | | - |
45 | | -하나의 파일에는 따옴표를 일관되게 사용하세요. `'` 또는 `"` 중 하나를 선택하고 그것만 사용하세요. |
46 | | -다만 `\\` 사용을 피하기 위해 같은 파일이더라도 다른 따옴표를 사용하는 것은 괜찮습니다. `gpylint` 가 이를 검사합니다. |
47 | | - |
48 | | -```python |
49 | | -올바른 에시: |
50 | | - Python('Why are you hiding your eyes?') |
51 | | - Gollum("I'm scared of lint errors.") |
52 | | - Narrator('"Good!" thought a happy Python reviewer.') |
53 | | -``` |
54 | | - |
55 | | -```python |
56 | | -잘못된 예시: |
57 | | - Python("Why are you hiding your eyes?") |
58 | | - Gollum('The lint. It burns. It burns us.') |
59 | | - Gollum("Always the great lint. Watching. Watching.") |
60 | | -``` |
61 | | - |
62 | | -다수의 문장을 이용할 때는 `'''` 보단 `"""` 를 이용하세요. |
63 | | -프로젝트에 따라 docstring이 아닌 다른 여러줄의 문자열을 `'''` 를 이용하여 작성할 수 있습니다. |
64 | | -docstring은 상황과 무관하게 `"""` 를 사용합니다. |
65 | | -여러줄의 문자열은 나머지 코드의 들여쓰기와 잘 호환되지 않기에 |
66 | | -종종 묵시적인 라인결합 방식을 사용하는 것이 전체적으로 더 깔끔해 보인다는 점을 알아두세요. |
67 | | - |
68 | | -```python |
69 | | - 올바른 예시: |
70 | | - print("This is much nicer.\n" |
71 | | - "Do it this way.\n") |
72 | | -``` |
73 | | - |
74 | | -```python |
75 | | - 잘못된 예시: |
76 | | - print("""This is pretty ugly. |
77 | | -Don't do this. |
78 | | -""") |
79 | | -``` |
| 49 | + ``` |
| 50 | + |
| 51 | +- 하나의 파일에는 따옴표를 일관되게 사용하세요. `'` 또는 `"` 중 하나를 선택하고 그것만 사용하세요. |
| 52 | +- 다만 `\\` 사용을 피하기 위해 같은 파일이더라도 다른 따옴표를 사용하는 것은 괜찮습니다. `gpylint` 가 이를 검사합니다. |
| 53 | + |
| 54 | + - 올바른 예 |
| 55 | + |
| 56 | + ```python |
| 57 | + Python('Why are you hiding your eyes?') |
| 58 | + Gollum("I'm scared of lint errors.") |
| 59 | + Narrator('"Good!" thought a happy Python reviewer.') |
| 60 | + ``` |
| 61 | + |
| 62 | + - 부적절한 예 |
| 63 | + |
| 64 | + ```python |
| 65 | + Python("Why are you hiding your eyes?") |
| 66 | + Gollum('The lint. It burns. It burns us.') |
| 67 | + Gollum("Always the great lint. Watching. Watching.") |
| 68 | + ``` |
| 69 | + |
| 70 | +- 다수의 문장을 이용할 때는 `'''` 보단 `"""` 를 이용하세요. |
| 71 | +- 프로젝트에 따라 docstring이 아닌 다른 여러줄의 문자열을 `'''` 를 이용하여 작성할 수 있습니다. |
| 72 | +- docstring은 상황과 무관하게 `"""` 를 사용합니다. |
| 73 | +- 여러줄의 문자열은 나머지 코드의 들여쓰기와 잘 호환되지 않기에 종종 묵시적인 라인결합 방식을 사용하는 것이 전체적으로 더 깔끔해 보인다는 점을 알아두세요. |
| 74 | +- If you need to avoid embedding extra space in the string, use either concatenated single-line strings or a multi-line string with [`textwrap.dedent()`](https://docs.python.org/3/library/textwrap.html#textwrap.dedent) to remove the initial space on each line |
| 75 | +
|
| 76 | + - 부적절한 예 |
| 77 | +
|
| 78 | + ```python |
| 79 | + long_string = """This is pretty ugly. |
| 80 | + Don't do this. |
| 81 | + """ |
| 82 | + ``` |
| 83 | +
|
| 84 | + - 올바른 예 |
| 85 | +
|
| 86 | + ```python |
| 87 | + long_string = """This is fine if your use case can accept |
| 88 | + extraneous leading spaces.""" |
| 89 | + ``` |
| 90 | +
|
| 91 | + ```python |
| 92 | + long_string = ("And this is fine if you can not accept\n" + |
| 93 | + "extraneous leading spaces.") |
| 94 | + ``` |
| 95 | +
|
| 96 | + ```python |
| 97 | + long_string = ("And this too is fine if you can not accept\n" |
| 98 | + "extraneous leading spaces.") |
| 99 | + ``` |
| 100 | +
|
| 101 | + ```python |
| 102 | + import textwrap |
80 | 103 |
|
| 104 | + long_string = textwrap.dedent("""\ |
| 105 | + This is also fine, because textwrap.dedent() |
| 106 | + will collapse common leading spaces in each line.""") |
| 107 | + ``` |
0 commit comments