[Python-Basic] zfill, rjust, ljust - 문자열 채우기

조상래·2021년 5월 13일
0

python

목록 보기
1/8

문자열을 원하는 길이 만큼 채우고 싶을 때 사용.

1. 문자열.zfill()

n = '1'
print(n.zfill(5)) # 00001

n = 'a'
print(n.zfill(5)) # 0000a

n = 0
print(n.zfill(3)) # AttributeError: 'int' object has no attribute 'zfill'

위의 예시처럼 기존의 문자열 포함 원하는 길이만큼 기존 문자열 왼쪽으로 0('Z'ero)을 채워주는(fill) 함수이다.

주의할 점은 문자열의 형태만 가능하다.

그렇다면 0이 아닌 다른 문자열을 넣고싶다면 어떻게 할까?

2. 문자열.rjust() / ljust()

n = 'a'
print(n.rjust(5, 'b')) # aaaab
print(n.ljust(3, 'c')) # acc

print(n.ljust(3, 'df')) #  TypeError: The fill character must be exactly one character long

n = '1'
print(n.rjust(2, 12)) # TypeError: The fill character must be a unicode character, not int

n = 0
prunt(n.ljust(3, '1')) # AttributeError: 'int' object has no attribute 'rjust'

rjust는 기존 문자열을 오른쪽으로 정렬하고 두 번째의 인자로 들어오는 문자열을 첫 번째 인자의 길이만큼 입력

ljust는 반대로 기존 문자열을 왼쪽으로 정렬한다.

주의점은 zfill과 마찬가지로 문자열의 형태로만 가능하고 두 번째 인자로 오는 문자열의 길이는 무조건 1로 제한된다.

profile
Codestates Full IM26기 수료

0개의 댓글