[python] string rjust, ljust 사용법



python string rjust & ljust 사용법


1. string.rjust


rjust는 오른쪽으로 문자열을 정렬해주는 함수입니다.
원본 string을 제외하고 width에 입력된 길이만큼 fillchar의 문자를 왼쪽부터 채워 넣어줍니다.

Parameter

1. width
string 원본에서 오른쪽으로 얼마나 정렬할 지 길이를 설정합니다.
만약 width가 명시된 string 길이보다 같거나 짧다면 원본 string을 반환합니다.

2. fillchar (optional)
padding으로 채울 문자를 입력합니다.
만약 fillchar를 입력하지 않으면 공백으로 정렬합니다.

Example

test_string = 'test'
print(test_string.rjust(10))

# 출력
#       test
width를 10, fillchar를 명시하지 않아 '공백' 6칸을 넣어 'test' 문자를 오른쪽으로 정렬

test_string = 'test'
print(test_string.rjust(10, '#'))

# 출력
# ######test
width를 10, fillchar를 '#'으로 명시했기 때문에 '#' 6칸을 넣어 'test' 문자를 오른쪽으로 정렬

test_string = 'test'
print(test_string.rjust(2, '#'))

# 출력
# test
width를 2, fillchar를 '#'으로 명시했는데 width가 'test'의 길이보다 작기 때문에 원본 'test'를 반환




2. string.ljust



ljust는 왼쪽으로 문자열을 정렬해주는 함수입니다.
Parameter의 역할은 rjust와 동일합니다.

Example

test_string = 'test'
print(test_string.ljust(10))
print(test_string.ljust(10, '#'))
print(test_string.ljust(2, '#'))

# 출력
# test
# test######
# test


참고문헌

[1] https://docs.python.org/3/library/stdtypes.html


댓글

이 블로그의 인기 게시물

[opencv-python] 이미지 크기조절(resize) 하는 법

[python] selenium close와 quit 차이점

[python]파이썬: csv reader header skip (첫번째 행 무시하기, 안읽기)