코딩, 개발에 대한 기록 저장소

파이썬(Python) 문자열 보기 좋게 출력하기

파이썬(Python) 문자열 보기 좋게 출력하기

출력되는 문자열의 길이가 다를때 정렬과 공백을 사용하여 출력을 보기 좋게 처리

왼쪽 정렬

python
s = '%-10s' % 'apple'               # -를 붙여 왼쪽 정렬

print(s)
print(s.replace(' ','0'))

결과


apple    
apple0000

오른쪽쪽 정렬

python
s = '%10s' % 'apple'

print(s)
print(s.replace(' ','0'))

결과


    apple
0000apple

정렬과 공백으로 보기 좋게 출력

python
fruit = [('apple', 12), ('strawberry', 1234), ('melon', 5), ('banana', 102)]
for item in fruit:
    str = '%-10s%10s' % (item[0], item[1])
    print(str)

결과


apple             12
strawberry      1234
melon              5
banana           102