Python
문자열 응용
haventmetyou
2023. 10. 10. 12:45
문자열 조작
>>> # 문자열 바꾸기 replace('바꿀문자열', '새문자열')
>>> 'Hello, world!' .replace('world', 'Python')
'Hello, Python!'
>>> # 바꾼 문자열 유지
>>> s = 'Hello, world!'
>>> s = s.replace('world', 'Python')
>>> print(s)
Hello, Python!
>>>
>>> # 문자 바꾸기 str.maketrans('바꿀문자', '새문자')
>>> table = str.maketrans('aeiou', '12345')
>>> 'apple'.translate(table)
'1ppl2'
>>>
>>> # 문자열 분리하기
>>> 'apple pear grape pineapple orange'.split()
['apple', 'pear', 'grape', 'pineapple', 'orange']
>>>
>>> # 구분자 문자열과 문자열 리스트 연결
>>> # join(리스트)는 구분자 문자열과 문자열 리스트의 요소를 연결해 문자열로 만듦
>>> ' '.join(['apple', 'pear', 'grape', 'pineapple', 'orange'])
'apple pear grape pineapple orange'
>>> '-'.join(['apple', 'pear', 'grape', 'pineapple', 'orange'])
'apple-pear-grape-pineapple-orange'
>>>
>>> # 소문자 - 대문자 변환
>>> 'python'.upper()
'PYTHON'
>>> # 대문자 - 소문자 변환
>>> 'PYTHON'.lower()
'python'
>>>
>>> # 공백 삭제 lstrip, rstrip, strip 메서드 사용
>>> ' Python '.lstrip() # 왼쪽 공백 삭제
'Python '
>>> ' Python '.rstrip() # 오른쪽 공백 삭제
' Python'
>>> ' Python '.strip() # 양쪽 공백 삭제
'Python'
>>>
>>> # 특정 문자 삭제
>>> ', python.'.lstrip(',.')
' python.'
>>> ', python.'.rstrip(',.')
', python'
>>> ', python.'.strip(',.')
' python'
>>>
>>> # 구두점 간단 삭제
>>> import string
>>> ', python.'.strip(string.punctuation)
' python'
>>> print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
>>> ', python.'.strip(string.punctuation + ' ') # 공백까지 삭제
'python'
>>>
>>> # 문자열 정렬 ljust(길이), rjust(길이), center(길이)
>>> 'python'.ljust(10)
'python '
>>> 'python'.rjust(10)
' python'
>>> 'python'.center(10)
' python '
>>>
>>> # 메서드 체이닝(메서드를 줄줄이 연결)
>>> 'python'.rjust(10).upper()
' PYTHON'
>>>
>>> # 문자열 왼쪽에 0 채우기 zfill(길이)
>>> # zfill = zero fill
>>> '35'.zfill(4)
'0035'
>>> '3.5'.zfill(6)
'0003.5'
>>> 'hello'.zfill(10) # 문자열 앞에 0 채울 수 있음
'00000hello'
>>>
>>> # 문자열 위치 찾기 find('찾을문자열')
>>> 'apple pineapple'.find('pl') # 여러 개일 경우 처음 찾은 문자열의 인덱스를 반환
2
>>> 'apple pineapple'.find('xy')
-1
>>> 'apple pineapple'.rfind('pl') # 오른쪽에서부터 문자열 위치 찾기
12
>>> 'apple pineapple'.rfind('xy')
-1
>>> # 문자열 위치 찾기 index('찾을문자열'), rindex('찾을문자열')
>>> 'apple pineapple'.index('pl')
2
>>> 'apple pineapple'.rindex('pl') # 오른쪽에서부터 문자열 위치 찾기
12
>>>
>>> # 문자열 개수 세기 count('문자열')
>>> 'apple pineapple'.count('pl')
2
>>>
문자열 서식 지정자와 포매팅
서식 지정자
>>> # 서식 지정자 문자 %s
>>>
>>> 'I am %s.' % 'James'
'I am James.'
>>> name = 'Maria'
>>> 'I am %s' % name
'I am Maria'
>>>
>>> # 서식 지정자 숫자 %d
>>>
>>> 'I am %d years old' %20
'I am 20 years old'
>>> 'I am %s years old' %20
'I am 20 years old'
>>> 'I am %s years old' % '20'
'I am 20 years old'
>>>
>>> # 소수점 %f
>>> '%f' % 2.3
'2.300000'
>>> '%d' % 2.3
'2'
>>> '%s' % 2.3
'2.3'
>>> print('%f' %2.3)
2.300000
>>> '%.2f' % 2.3 # 소수점 이하 자릿수 '%.자릿수f' % 숫자
'2.30'
>>> '%.3f' % 2.3
'2.300'
>>> '%0.2f' % 2.3
'2.30'
>>> '%3.2f' % 2.3
'2.30'
>>> '%2.2f' % 1232.3
'1232.30'
>>>
>>> # 서식 지정자로 문자열 정렬
>>>
>>> 'python'.rjust(10)
' python'
>>> '%10s' % 'python'
' python'
>>>
>>> '%10d' % 150 # 자릿수 다른 숫자 출력 ex) 돈 계산
' 150'
>>> '%10d' % 15000
' 15000'
>>>
... '%10.2f' % 2.3 # 실수는 '%길이.자릿수f'
' 2.30'
>>> '%10.2f' % 2000.3
' 2000.30'
>>> '%.2f' % 2.3
'2.30'
>>>
>>> '%-10s' % 'python' # 왼쪽 정렬 '%-길이s'
'python '
>>>
>>> # 서식 지정자로 문자열 안에 값 여러 개 넣기
>>> 'Today is %d %s.' % (10, 'Oct')
'Today is 10 Oct.'
>>> 'Today is %d%s.' % (10, 'Oct')
'Today is 10Oct.'
>>> 'Today is %s %s.' % (10, 'Oct')
'Today is 10 Oct.'
>>> 'Today is %d %d.' % (10, 'Oct')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a real number is required, not str
>>>
포매팅 format 메서드 사용
>>> 'Hello, {0} {2} {1}'.format('Python', 'Script', 3.6)
'Hello, Python 3.6 Script'
>>> '{0}{0}{1}{1}' .format('Python','Script') # 값 여러 개 넣기
'PythonPythonScriptScript'
>>> '%s %s %s %s' % ('Python', 'Python', 'Script', 'Script')
'Python Python Script Script'
>>>
>>> 'Hello, {} {} {}'.format('짜장면', '짬뽕', '탕수육') # 인덱스 생략
'Hello, 짜장면 짬뽕 탕수육'
>>>
>>> 'Hello, {lang} {ver}' .format(lang = 'Python', ver=3.6)
'Hello, Python 3.6'
>>>
>>>>>> # f-문자열 포매팅
>>> language = 'Python'
>>> version = 3.6
>>> f'Hello, {language} {version}' # 문자열 포매팅에 변수 그대로 사용
'Hello, Python 3.6'
>>> '동물원에는 {{ {} }} {{ {} }}' .format('사자', '호랑이') # 중괄호 출력
'동물원에는 { 사자 } { 호랑이 }'
>>>
>>> # format 메서드로 문자열 정렬
>>> '{0:<10}'.format('python')
'python '
>>> '{0:>10}'.format('python')
' python'
>>> '{:>10}'.format('python')
' python'
>>>
>>> # 숫자 개수 맞추기
>>> # '%0개수d' % 숫자 혹은 '{인덱스:0개수d}'.format(숫자)
>>> # 실수 맞추기
>>> # '%0개수.자릿수f' % 숫자 혹은 '{인덱스:0개수.자릿수f}'.format(숫자)
>>> '%03d' % 1
'001'
>>> '{0:03d}'.format(35)
'035'
>>>
>>> '%d08.2f' %3.6
'308.2f'
>>> '{0:08.2f}'.format(150.37)
'00150.37'
>>> '{0:8.2f}'.format(150.37)
' 150.37'
>>> '%08.2f' % 3.6
'00003.60'
>>>
>>> # 채우기와 정렬 조합해 사용
# '{인덱스:[[채우기]정렬][길이][.자릿수][자료형]}'
>>> '{0:0<10}'.format(15)
'1500000000'
>>> '{0:0>10}'.format(15)
'0000000015'
>>> '{0:0>10.2f}'.format(15)
'0000015.00'
>>> '{0: >10}'.format(15)
' 15'
>>> '{0:*>10}'.format(15)
'********15'
>>>
>>> # 금액에 천 단위로 콤마 넣기
>>> format(1493500, ',')
'1,493,500'
>>> '%20s' % format(1493500, ',')
' 1,493,500'
>>> '{0:,}'.format(1493500)
'1,493,500'
>>> '{0:>20,}'.format(1493500)
' 1,493,500'
>>> '{0:0>20,}'.format(1493500)
'000000000001,493,500'
>>>