파이썬 프로그래밍 기초: 문자열 자료형

justyoon·2023년 4월 3일
0

이스케이프 코드(escape code)

  • 이스케이프 코드란 프로그래밍할 때 사용할 수 있도록 미리 정의해 둔 "문자 조합"이다. 주로 출력물을 보기 좋게 정렬하는 용도로 사용한다.

문자열 포맷 코드

How to concatenate?

%

# ex
print('%s %s' % ('one', 'two'))
print()
 
# one two

.format()

# ex
print('{} {}'.format('one', 'two'))
print('{0} {1}'.format('1','2'))
print('{1} {0}'.format('1','2')) # 인덱스 순서변경
print()

# one two
# 1 2
# 2 1

%d

# ex
print('%d %d' %(1,2))
print('{} {}'.format(1,2))
print('%4d' %(42))
print('{:4d}'.format(42)) # 정수일 때 자리수 뒤에 d를 꼭 표시
print()

# 1 2
# 1 2
#   42
#   42

%f

# ex
print('%f' % (3.14159265)) #default 값 = 정수부 1자리, 소수부 8자리
print('%.4f' % (3.141592)) #소수부 4자리까지
print('{:f}'.format(3.1415926535))
print()

# 3.141593
# 3.1416
# 3.141593
  • 응용
# ex
print('%06.2f' % (3.1415926535)) #정수부 앞은 0으로 표현 소수부는 2자리까지 표현하고 총 자리수를 6으로 맞춤
print('% 6.2f' % (3.1415926535)) #정수부 앞 빈자리는 공백으로 채우고 총 자리수 6으로 맞춤
print('%06.4f' % (3.1415926535)) #정수부 앞자리 0은 총 자리수 4에서 우선순위로 소수부에 밀린다
print()

# 003.14
# 	3.14
# 3.1416

%s

  • 오른쪽 정렬
# ex
print('%10s' % ('nice!')) #%s의 s앞에는 자리수. 공백 5자리, 지정한 문자열 5자리
print('%10s' % ('nice to meet you!')) #문자열 정렬도 마찬가지로 지정한 문자열이 우선순위이다
print('%20s' % ('nice to meet you!')) 
print('{:>10}'.format('nice')) #%10s와 동일한 .format()
print()

#     nice!
# nice to meet you!
#   nice to meet you!
#      nice
  • 왼쪽 정렬
# ex
print('%-10s' % ('nice')) #10자리수 단어를 왼쪽부터 출력
print('{:_<10}'.format('nice')) #10자리수 단어를 오른쪽부터 _출력
print()

# nice
# nice______
  • 가운데 정렬
# ex
print('%^10s' % ('happy')) -> Error
print('{:^10s}'.format ('happy'))

#   happy
profile
with gratitude, optimism is sustainable

0개의 댓글