728x90
반응형
문자열 포맷팅 방식에는 3가지가 있다.
1) % operator
2) .format()
3) f-string
1. % operator
- 문자열에 숫자, 문자열을 대입할 수 있음
- 소수점 표현 가능
- 문자열 정렬 가능
- c언어 스타일
#숫자 대입
print('hello world! my age is %d' % 20)
>>> hello world! my age is 20
#문자 대입
print('hi %s, my name is dabong' % 'jinny')
>>> hi jinny, my name is dabong
#값 여러개 대입
print('hi, my name is %s and age is %d.' % ('dabong', 28)
>>> hi, my name is dabong and age is 28.
# 소수점 표현
# 형식 : '%.자릿수f' % 표현할 숫자
print('%.2f' % 3)
>>> 3.00
# 문자열 오른쪽 정렬
# 형식 : '%문자열 길이s' % '문자열' ==> 오른쪽 정렬
print('%10s' % 'hello')
>>> ' hello'
# 문자열 왼쪽 정렬
# 형식 : '%문자열 길이s' % '문자열' ==> 오른쪽 정렬
print('%-10s' % 'hello')
>>> 'hello '
2. format 함수 사용
- 더 간단한 방식
- 형식 : '{인덱스} blabla'.format('문자열' 또는 숫자)
- 인덱스 생략 가능
- 인덱스 대신 이름 지정 가능
#숫자 대입
print('Hi, my age is {0}'.format(28))
>>> Hi, my age is 28
# 문자열 대입
print('Hi, my name is {0}'.format('dabong'))
>>> Hi, my name is dabong
# 값 여러개 대입
print('Hi {2}, my name is {0} and age is {1}'.format('dabong', 28, 'tom')
>>> Hi tom, my name is dabong and age is 28
# 인덱스 생략 ==> format에 지정한 순서대로 값이 들어감.
print('{} {} {}'.format('hello', 'world', '!'))
>>> hello world !
# 인덱스 대신 이름 지정
print('내 파이썬 : {lang} {version}'.format(lang='python', version='3.7'))
>>> 내 파이썬 : python 3.7
3. f-string
- python 3.6 버전부터 사용 가능
- 변수를 그대로 사용 가능
lang = 'python'
version = '3.7'
# 숫자, 문자열 대입
print(f'{lang} and {ver}')
>>> python and 3.7
# 중괄호 출력
print(f'{{ {lang} }}')
>>> { python }
# 배열 출력
arr = ['hello', 'world']
print(f'{arr[1]}')
>>> world
# 문자열 정렬하기
# 부등호 방향 + 자리수로 정렬
# 변수:^10 (가운데 정렬) | 변수:<10(왼쪽 정렬) | 변수:>10(오른쪽 정렬) # 10자리수
print('print(f"'{lang:<10}'")
>>> 'python '
print(f'|{lang:<10}|')
>>> |python |
print(f'|{lang:>20}|')
>>>| python|
# 채우기와 정렬
# f'{숫자:빈 자리 채울 숫자 또는 문자<총 자리수}'
print(f'{num:0<10}')
>>> 1230000000
728x90
반응형
'PYTHON' 카테고리의 다른 글
[python3] 4. 리스트 컴프리헨션 (0) | 2021.03.08 |
---|---|
[python3] 9. 로컬 모든 변수 조회 (0) | 2021.03.08 |
[python3] 2. 나눗셈 (몫, 나머지 연산) (0) | 2021.03.08 |
[python3] 1. 입력, 출력 (0) | 2021.03.08 |
[PYTHON] 파이썬으로 배우는 딥러닝 교과서 (0) | 2020.11.03 |