갈루아의 반서재

문자열은 파이썬 시퀀스 타입의 하나이며, 불변immutable 이다.

 

문자열의 생성

  • 단일인용부호 또는 이중인용부호로 생성할 수 있다.
  • 2가지 인용부호가 존재하는 이유는 인용부호가 포함된 문자열을 만들기 위해서이다.
>>> 'second'
'second'
>>> "minute"
'minute'
>>>
  • 3개의 단일인용부호 혹은 3개의 이중인용부호는 여러 줄의 문자열에 사용한다. 
  • 3개의 단일인용부호 안에 여러 줄이 있는 경우, 문자열 끝에 들어 있는 라인 끝 문자는 보존된다. 그리고 양쪽 끝에 공백이 있는 경우에도 보존된다.
>>> blake = '''In seed time learn, in harvest teach, in winter enjoy.
...    Drive your cart and your plow over the bones of the dead.
... The road of excess leads to the palace of wisdom.
... Prudence is a rich ugly old maid courted by Incapacity.
... He who desires but acts not, breeds pestilence.
... The cut worm forgives the plow.
...    Dip him in the river who loves water.
... A fool sees not the same tree that a wise man sees.
... He whose face gives no light, shall never become a star.
... Eternity is in love with the productions of time.
... The busy bee has no time for sorrow.
... The hours of folly are measur'd by the clock, but of wis­dom: no clock can measure.
... All wholsom food is caught without a net or a trap.
... Bring out number weight & measure in a year of dearth.
... No bird soars too high, if he soars with his own wings.
... A dead body, revenges not injuries.
... The most sublime act is to set another before you.
... If the fool would persist in his folly he would become wise.
... Folly is the cloke of knavery.
... Shame is Prides cloke.
... '''

대화식 인터프리터 출력 결과 - 단일 인용부호 또는 \n 과 같은 escape character 가 들어있는 문자열 출력 가능

>>> blake
"In seed time learn, in harvest teach, in winter enjoy.\n   Drive your cart and your plow over the bones of the dead.\nThe road of excess leads to the palace of wisdom.\nPrudence is a rich ugly old maid courted by Incapacity.\nHe who desires but acts not, breeds pestilence.\nThe cut worm forgives the plow.\n   Dip him in the river who loves water.\nA fool sees not the same tree that a wise man sees.     \nHe whose face gives no light, shall never become a star.\nEternity is in love with the productions of time.\nThe busy bee has no time for sorrow.\nThe hours of folly are measur'd by the clock, but of wis\xaddom: no clock can measure.\nAll wholsom food is caught without a net or a trap.\nBring out number weight & measure in a year of dearth.\nNo bird soars too high, if he soars with his own wings.\nA dead body, revenges not injuries.\nThe most sublime act is to set another before you.\nIf the fool would persist in his folly he would become wise.\nFolly is the cloke of knavery.\nShame is Prides cloke.\n"
>>>

print() 출력 결과

  • 인용부호를 제거한 뒤 내용 출력한다.
  • 출력할 것들 사이의 공백과 줄바꿈을 유용하게 추가 가능하다.
>>> print(blake)
In seed time learn, in harvest teach, in winter enjoy.
   Drive your cart and your plow over the bones of the dead.
The road of excess leads to the palace of wisdom.
Prudence is a rich ugly old maid courted by Incapacity.
He who desires but acts not, breeds pestilence.
The cut worm forgives the plow.
   Dip him in the river who loves water.
A fool sees not the same tree that a wise man sees.
He whose face gives no light, shall never become a star.
Eternity is in love with the productions of time.
The busy bee has no time for sorrow.
The hours of folly are measured by the clock, but of wisdom: no clock can measure.
All wholsom food is caught without a net or a trap.
Bring out number weight & measure in a year of dearth.
No bird soars too high, if he soars with his own wings.
A dead body, revenges not injuries.
The most sublime act is to set another before you.
If the fool would persist in his folly he would become wise.
Folly is the cloke of knavery.
Shame is Prides cloke.

빈문자열 생성 - 여러 문자열을 한 문자열로 합칠 때 문자열 사이에 공백을 입력할 때 유용

>>> ''
''
>>> ""
''
>>> ''''''
''
>>> """"""
''
>>>

데이터 타입 변환

  • str() 함수를 이용하여 데이터 타입을 문자열로 변환가능
  • 문자열이 아닌 객체를 print() 로 호출할 때, 파이썬은 내부적으로 str() 함수를 사용함
  • 변수나 상수를 문자열 안에 삽입하는 문자열 보간string interpolation 시에도 내부적으로 사용함 

이스케이프 문자

\n (줄바꿈)

>>> str = 'One,\nTwo,\nThree'
>>> print(str)
One,
Two,
Three
>>>

\t (t는 tab을 의미함)

>>> print('abc')
abc
>>> print('\tabc')
        abc
>>> print('a\tbc')
a       bc
>>> print('ab\tc')
ab      c
>>> print('abc\t')
abc
>>>

\' 또는 \" 를 사용하여 단일 또는 이중부호 표시 가능

>>> title = 'How to combine multiple CSV files with \'8\' lines of code'
>>> print(title)
How to combine multiple CSV files with '8' lines of code
>>>

백슬래시를 2번 입력하면 백슬래시 출력 가능

>>> title = 'How to combine multiple CSV files with 8 lines of code\\'
>>> print(title)
How to combine multiple CSV files with 8 lines of code\
>>>

문자열의 결합

  • + 연산자를 사용하여 리터럴 문자열 또는 문자열 변수를 결합할 수 있다 
  • 문자열 결합시 공백을 자동으로 붙이지 않는다
  • print()  는 각 인자 사이에 공백을 붙인다.

문자열의 복제

  • * 연산자를 이용하여 문자열 복제 가능
>>> start = 'Na   ' * 4 + '\n'
>>> middle = 'Hey   ' * 3 + '\n'
>>> end = 'Goodbye.'
>>> print(start + start + middle + end)
Na   Na   Na   Na
Na   Na   Na   Na
Hey   Hey   Hey
Goodbye.
>>>

문자 추출

  • [ ] 와 오프셋을 이용하여 문자열에서 한 문자를 얻을 수 있다.
  • 가장 왼쪽이 0 이고, 그 다음은 1, 2, ..... 이런 식이다. 
  • 가장 오른쪽 오프셋은 -1 이다. 그 다음은 -2, -3 이다.
0 1 2 3 .........     -3 -2 -1
>>> letters = 'dhkdhdkjdidhdkjdkdjhdkjdkdjkdjdkd'
>>> letters[0]
'd'
>>> letters[1]
'h'
>>> letters[-1]
'd'
>>> letters[-2]
'k'
>>>

오프셋을 문자열의 길이 이상으로 지정하는 경우 에러 발생

>>> letters[100]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>>

문자열은 앞서 언급했듯이 불변immutable 로 문자를 삽입하거나 변경할 수 없다. 

>>> name = 'Henny'
>>> name[0] = 'P'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>

대신 replace() 및 슬라이스와 같은 문자열 함수를 사용하여 표현할 수 있다.

>>> name = 'Henny'
>>> name.replace('H', 'P')
'Penny'
>>> 'P' + name[1:]
'Penny'
>>>

슬라이스

  • 슬라이스를 사용하여 문자열의 일부substring 을 추출할 수 있다
  • [ start : end : step ] 로 슬라이스를 정의한다. 오프셋의 start 와 end-1 사이의 문자를 포함한다.

[ : ] 처음부터 끝까지 시퀀스 추출

[ start : ] start 오프셋부터 끝까지 시퀀스 추출

[ : end ] 처음부터 (end-1) 오프셋까지 시퀀스 추출

[ start : end  ] start 오프셋부터 (end-1) 오프셋까지 시퀀스 추출

[ start : end : step ] step 만큼 문자를 건너뛰면서 start 오프셋부터 (end-1) 오프셋까지 시퀀스 추출

오프셋 0 1 2 3 4 5 6 7 8 9 10 11 ...... -6 -5 -4 -3 -2 -1
문자열 W h a t A r e H a s h T a b l e s a n

문자열 전체 출력

>>> letters = 'WhatAreHashTablesan'
>>> letters[:]
'WhatAreHashTablesan'

오프셋 3부터 끝까지 출력

>>> letters[3:]
'tAreHashTablesan'

오프셋 6부터 끝까지 출력

>>> letters[6:]
'eHashTablesan'

오프셋 7부터 10까지 출력

>>> letters[7:11]
'Hash'

마지막 세 문자 출력

>>> letters[-3:]
'san'

오프셋 7부터 마지막 네 번째 문자까지 출력

>>> letters[7:-3]
'HashTable'

끝에서 6번째 문자부터 3번째 문자까지 출력

>>> letters[-6:-2]
'bles'

3번째부터 10번째까지 2스텝씩 건너뛰면서 출력

>>> letters[3:11:2]
'trHs'

5번째부터 끝까지 3스텝씩 건너뛰면서 출력

>>> letters[5::3]
'raTla'

처음부터 12번째까지 3스텝씩 건너뛰면서 출력

>>> letters[:13:3]
'Wtesa'

끝에서부터 시작지점까지 빠짐없이 문자 출력

>>> letters[::-1] 
'naselbaThsaHerAtahW'

끝에서 10번째부터 끝까지 출력

>>> letters[-10:]
'shTablesan'

끝에서 11번째부터 끝에서 10번째까지 출력

>>> letters[-11:-10]
'a'

문자열 길이

  • len()

문자열 나누기

  • split() 는 구분자를 기준으로 하나의 문자열을 작은 문자열들의 리스트로 나눈다
  • 문자열에 특정한 함수로, 형태는 string.function(arguments) 와 같다
>>> tools = 'get gloves, get mask, give cat vitamins'
>>> tools.split(',')
['get gloves', ' get mask', ' give cat vitamins']
>>>

구분자를 지정하지 않으면 문자열에 등장하는 공백문자(줄바꿈, 스페이스, 탭)을 사용한다.

>>> tools.split()
['get', 'gloves,', 'get', 'mask,', 'give', 'cat', 'vitamins']
>>>

문자열 결합하기

  • join() 함수는 문자열 리스트를 하나의 문자열로 결합한다.
  • string.join(list) 형태로 결합한다
  • lines 리스트를 각각 줄바꿈하여 하나의 문자열로 결합하기 위해서는 '\n'.join(lines) 를 입력한다
>>> cryptocurrency_list = ['BTC','BNB','ETH','XRP','BCH']
>>> cryptocurrency_string = ', '.join(cryptocurrency_list)
>>> print('Cryptocurrency name:', cryptocurrency_string)
Cryptocurrency name: BTC, BNB, ETH, XRP, BCH
>>>

문자열 다루기

다음 윌리엄 블레이크의 시를 통해 일반적인 문자열 함수에 대해 살펴보자.

>>> poem = '''In seed time learn, in harvest teach, in winter enjoy.
...    Drive your cart and your plow over the bones of the dead.
... The road of excess leads to the palace of wisdom.
... Prudence is a rich ugly old maid courted by Incapacity.
... He who desires but acts not, breeds pestilence.
... The cut worm forgives the plow.
...    Dip him in the river who loves water.
... A fool sees not the same tree that a wise man sees.
... He whose face gives no light, shall never become a star.
... Eternity is in love with the productions of time.
... The busy bee has no time for sorrow.
... The hours of folly are measured by the clock, but of wisdom: no clock can measure.
... All wholsom food is caught without a net or a trap.
... Bring out number weight & measure in a year of dearth.
... No bird soars too high, if he soars with his own wings.
... A dead body, revenges not injuries.
... The most sublime act is to set another before you.
... If the fool would persist in his folly he would become wise.
... Folly is the cloke of knavery.
... Shame is Prides cloke.'''
>>>

스페이스와 줄바꿈을 포함한 이 시의 전체 길이

>>> len(poem)
986

이 시는  In 으로 시작하는가, 그리고 That's all 로 끝나는가

>>> poem.startswith('In')
True
>>> poem.endswith('That\'s all')
False
>>>

첫 번째로 the 가 나오는 오프셋

>>> word = 'the'
>>> poem.find(word)
93
>>>

마지막 the  가 나오는 오프셋

>>> word = 'the'
>>> poem.rfind(word)
942
>>>

the 는 몇 번 나오는가

>>> word = 'the'
>>> poem.count(word)
11
>>>

이 시는 글자와 숫자만으로 이루어졌는가

>>> word = 'the'
>>> poem.isalnum()
False
>>>

대소문자와 배치

양 끝에서 . 시퀀스를 제거한다.

>>> test = 'tuples are very handy to use in Python programming...'
>>> test.strip('.')
'tuples are very handy to use in Python programming'

첫 번째 단어를 대문자로 만든다.

>>> test.capitalize()
'Tuples are very handy to use in python programming...'

모든 단어의 첫 글자를 대문자로 만든다.

>>> test.title()
'Tuples Are Very Handy To Use In Python Programming...'

글자를 모두 대문자로 만든다.

>>> test.upper()
'TUPLES ARE VERY HANDY TO USE IN PYTHON PROGRAMMING...'

글자를 모두 소문자로 만든다.

>>> test.lower()
'tuples are very handy to use in python programming...'

대문자는 소문자로, 소문자는 대문자로 만든다.

>>> test.swapcase()
'TUPLES ARE VERY HANDY TO USE IN pYTHON PROGRAMMING...'

문자열을 지정한 공간에서 중앙에 배치한다.

>>> test.center(100)
'                       tuples are very handy to use in Python programming...                        '

왼쪽에 배치한다.

>>> test.ljust(100)
'tuples are very handy to use in Python programming...                                               '

오른쪽에 배치한다.

>>> test.rjust(100)
'                                               tuples are very handy to use in Python programming...'

대체하기

  • replace() 를 통해 문자열의 일부를 대체할 수 있다
  • 인자로 바꿀 문자열, 대체할 새 문자열, 바꿀 문자열에 대한 횟수를 입력한다
  • 마지막 인자 횟수를 생략하면 첫 번째 인스턴스만 바꾼다
>>> test.replace('Python','Haskell')
'tuples are very handy to use in Haskell programming...'