Programming/Python

[Python] 유용한 문자열 함수들

※ 해당 글은 dojang.io/mod/page/view.php?id=2299을 참고하여 작성하였습니다.

 

저의 기준 사용 빈도가 높은 함수들

  • replace
>>> 'sample setence'.replace(' ','_')

'sample_setence'

 

  • split
>>> 'sample one two three four five'.split()

['sample', 'one', 'two', 'three', 'four', 'five']
>>> 'one, two, three, four, five'.split(', ')

['one', 'two', 'three', 'four', 'five']

 

  • join
>>> ' '.join(['one','two','three','four','five'])

'one two three four five'
>>> ''.join(list('test'))

'test'

 

  • zfill
>>> '1'.zfill(2)

'01'

>>> # 실험 1 : 4자리보다 큰 수
>>> '35111'.zfill(4)

'35111'

 

  • strip
>>> '    \t\t sample  \t\t '.strip()

'sample'

>>> ',,,,, .....    sample  ,,,,, .....   '.strip(' ,.')

'sample'
>>> '    \t\t sample  \t\t '.lstrip()

'sample  \t\t '

>>> ',,,,, .....  sample  \t\t '.lstrip(' ,.')

'sample  \t\t '
>>> '    \t\t sample  \t\t '.rstrip()

'    \t\t sample'

>>> '\t\t sample  ,,,,, .....   '.rstrip(' ,.')

'\t\t sample'
>>> import string
>>> ', sample .'.strip(string.punctuation)

' sample '
>>> string.punctuation

'!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'
>>> ', sample.'.strip(string.punctuation + ' ')

'sample'

 

그 외 실용적인 함수들

  • maketrans
>>> table = str.maketrans('aeiou','12345')
>>> 'sample'.translate(table)

's1mpl2'

 

  • lower, upper
>>> 'SAMPLE'.lower()

'sample'

>>> 'sample'.upper()

'SAMPLE'

 

  • ljust, rjust, center 
>>> '1234'.ljust(10)

'1234      '

>>> '1234'.rjust(10)

'      1234'

>>> '1234'.center(10)

'   1234   '

 

  • find
>>> # 'en'이 두번 등장할 때
>>> 'sample sentence'.find('en')

8
>>> # 없는 문자 검색시
>>> 'sample sentence'.find('hi')

-1
>>> # 'en'이 두번 등장할 때 : 오른쪽에서 검색하기
>>> 'sample sentence'.rfind('en')

11

 

  • index
>>> 'sample sentence'.index('pl')

3

>>> 'sample sentence'.rindex('en')

11
>>> # index 함수로 없는 문장 검색시 index 함수로 없는 문장 검색시
>>> 'sample sentence'.index('hi')

'''
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-24d9d0954d3a> in <module>()
----> 1 'sample sentence'.index('hi')

ValueError: substring not found
'''

 

  • count
>>> 'sample sentence'.count('en')

2