# 문자열 바꾸기
greetings = 'Hello, world!'
# 변경 결과를 유지하려면 replace를 사용한 뒤 다시 변수에 할당
new_greetings = greetings.replace('world', 'Python')
print(greetings) # Hello, world!
print(new_greetings) # Hello, Python!
# 문자 바꾸기
table = str.maketrans('aeiou', '12345') # (바꿀 대상, 새문자)
print('apple'.translate(table)) # 1ppl2
print('abcdefghij'.translate(table)) # 1bcd2fgh3j
print(type(table)) # <class 'dict'>
print(table) # {97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
# 문자열 분리하기 - split 안의 매개변수를 기준으로 분리하여 리스트로 반환
sentence = 'apple pear grape pineapple orange'.split()
print(sentence) # ['apple', 'pear', 'grape', 'pineapple', 'orange']
# 문자열 리스트 연결하기
sentence = ['apple', 'pear', 'grape', 'pineapple', 'orange']
print(' '.join(sentence)) # apple pear grape pineapple orange
print('-'.join(sentence)) # apple-pear-grape-pineapple-orange
# 대소문자 변환
print('python'.upper()) # PYTHON
print('PYTHON'.lower()) # python
# 공백 삭제
print(' Python '.rstrip()) # ' Python'
print(' Python '.lstrip()) # 'Python '
print(' Python '.strip()) # 'Python'
# 특정 문자 삭제
print(', python.'.lstrip(',.')) # ' python.'
print(', python.'.rstrip(',.')) # ', python'
print(', python.'.strip(',.')) # ' python'
# 문자열 양쪽 구두점 삭제 - 공백이나 글자 사이 구두점은 사라지지 않는다.
import string
print(', p@y!t/ho#n.'.strip(string.punctuation)) # ' p@y!t/ho#n'
# 공백까지 삭제하기 - strip()
print(', python.'.strip(string.punctuation).strip())
print('python'.ljust(10)) # 'python '
print('python'.rjust(10)) # ' python'
print('python'.center(10)) # ' python '
print('python'.center(11)) # ' python ' 남는 공간이 홀수가 된다면 왼쪽에 한 칸 더 들어간다.
print('35'.zfill(4)) # 0035
print('3.5'.zfill(6)) # 0003.5
print('hello'.zfill(10)) # 00000hello
# 문자열 위치 찾기 - 찾는 문자열이 없으면 -1 반환
print('apple pineapple'.find('pl')) # 2
print('apple pineapple'.find('xy')) # -1
print('apple pineapple'.rfind('pl')) # 12
print('apple pineapple'.rfind('xy')) # -1
print('apple pineapple'.index('pl')) # 2 찾는 문자열이 없으면 에러 발생
print('apple pineapple'.rindex('pl')) # 12
print('apple pineapple'.count('pl')) # 2
문자열 안에서 특정 부분을 원하는 값으로 바꿀 때 사용한다.
name = 'heyrin'
print('I am %s' % name) # I am heyrin
age = 25
print('I am %d years old' % age) # I am 25 years old
print('I am %.2f years old' % age) # I am 25.00 years old
# 문자열 정렬 - 문자열 길이를 10으로 만든 뒤 문자열을 오른쪽으로 정렬
# 자릿수가 다른 숫자 출력 시 유용
print('%10s' % 'python')
print('%10d' % 150)
print('%10d' % 15000)
# 실수 > 길이.자릿수f
print('%10.2f' % 2.3)
print('%10.2f' % 2000.3)
# 결과
python
150
15000
2.30
2000.30
# 왼쪽 정렬 - 문자열 길이에 '-' 붙이기
print('%-10s' % 'python') # 'python '
# 문자열 안에 값 여러 개 넣기 - 괄호 안에 값을 콤마로 구분해서 넣는다.
print('Today is %dth %s.' % (7, 'Jan')) # Today is 7th Jan.
print('Hello, {0}'.format('world!'))
print('Hello, {0}'.format(100))
print('Hello, {0} {2} {1}'.format('Python', 'Script', 3.6)) # 인덱스와 값 순서 주목!
print('Hello, {} {} {}'.format('Python', 'Script', 3.6)) # 인덱스 생략하면 format순서대로
# 결과
Hello, world!
Hello, 100
Hello, Python 3.6 Script
Hello, Python Script 3.6
# 인덱스 대신 이름 지정하기
print('Hello, {language} {version}'.format(language='Python', version=3.6))
# 변수 사용하기
lang = 'Python'
version = 3.6
print(f'hello, {lang} {version}')
# 중괄호 출력하기
print('{{ {0} }}'.format('Python')) # { Python }
# 문자열 정렬하기 {인덱스:정렬방향(> or <)길이}
print('{0:<10}'.format('python'))
print('{0:>10}'.format('python'))
print('{:<10}'.format('python'))
# 결과
'python '
' python'
'python '
# 숫자 개수 맞추기
# '%0개수d' % 숫자
# '{인덱스:개수d}'.format(숫자)
# '%0개수.자릿수f' % 숫자
# '{인덱스:개수.자릿수f}'.format(숫자)
print('%03d' % 2) # 002
print('{0:03d}'.format(35)) # 035
# 실수는 숫자 개수에 정수부분, 소수점, 소수점이하 자릿수가 모두 포함된다.
print('%08.2f' % 3.6) # 00003.60
print('{0:08.2f}'.format(150.37)) # 00150.37
# 채우기, 정렬 조합
# '{[인덱스]:[채우기][정렬][길이][자릿수][자료형]}
print('{0:0<10}'.format(15)) # '1500000000'
print('{0:0>10.2f}'.format(15)) # '0000015.00'
print('{0: >10}'.format(15)) # ' 15' 채우기 부분에 공백
print('{0:>10}'.format(15)) # ' 15' 채우기 부분 생략 > 공백
# 천 단위로 콤마 넣기
print(format(1493500, ',')) # 1,493,500
print('{0:,}'.format(1493500)) # 1,493,500
print('{0:>20,}'.format(1493500)) # 길이 20, 천단위 콤마, 오른쪽 정렬