코딩테스트/Python 개념

[Python] 문자열 길이 지정하기 (.zfill(), .rjust(), format())

박소민 2022. 3. 8. 15:31
.zfill(n) : n칸이 되도록 문자열 앞에 0 채우는 함수
  • '문자열'.zfill(길이)
a='38'
print(a.zfill(5))
#결과
'00038'

 

.rjust(n,'문자'): n칸이 되도록 문자열 앞에 설정한 문자 삽입
  • '문자열'.rjust(길이, '문자')
a='38'
n=5
print(a.rjust(5,'0'))
print(a.rjust(n,'R'))
#결과
'00038'
'RRR38'

 

format함수 사용
  • '{인덱스:<길이}'.format('문자열')
    • < : 왼쪽 정렬
    • > : 오른쪽 정렬
    • 공백대신 다른 문자로 채울 수 있음
print('{0:<10}'.format('python'))
print('{0:>10}'.format('hello'))
print('{0:-<10}'.format('world'))
print('{1:->10}'.format('ball','cat'))
#결과
'python    '
'     hello'
'world-----'
'-------cat'

 

  • format( 숫자 , '(길이)진수표현')
    • 2진수 : format(숫자, 'b')
    • 8진수 : format(숫자, 'o')
    • 16진수 : format(숫자, 'x')
print(format(42,'8b'))
#결과
'  101010'