Python/Python 기본
[Python] 대소문자 변경과 공백 제거하는 명령어(lower, upper, strip 등)
이지IT
2023. 4. 21. 15:16
반응형
목록
- 대, 소문자 변경
- 공백 제거
대, 소문자 변경
1. str.lower(): 문자열의 모든 문자를 소문자로 변환합니다.
text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text) # Output: 'hello, world!'
2. str.upper(): 문자열의 모든 문자를 대문자로 변환합니다.
text = "Hello, World!"
uppercase_text = text.upper()
print(uppercase_text) # Output: 'HELLO, WORLD!'
3. str.capitalize(): 문자열의 첫 번째 문자를 대문자로 만들고 나머지는 소문자로 만듭니다.
text = "hello, world!"
capitalized_text = text.capitalize()
print(capitalized_text) # Output: 'Hello, world!'
4. str.title(): 문자열에서 각 단어의 첫 글자를 대문자로 하고 나머지는 소문자로 만듭니다.
text = "hello, world!"
title_text = text.title()
print(title_text) # Output: 'Hello, World!'
5. str.swapcase(): 문자열에 있는 각 문자의 대소문자를 바꿉니다(대문자에서 소문자로 또는 그 반대로).
text = "Hello, World!"
swapped_case_text = text.swapcase()
print(swapped_case_text) # Output: 'hELLO, wORLD!'
공백 제거
1. str.strip(): 문자열의 시작과 끝 모두에서 공백을 제거합니다.
text = " Hello, World! "
stripped_text = text.strip()
print(f"|{left_stripped_text}|") # Output: '|Hello, World!|'
2. str.lstrip(): 문자열의 시작 부분(왼쪽)에서 공백을 제거합니다.
text = " Hello, World! "
left_stripped_text = text.lstrip()
print(f"|{left_stripped_text}|") # Output: '|Hello, World! |'
3. str.rstrip(): 문자열의 끝(오른쪽)에서 공백을 제거합니다.
text = " Hello, World! "
right_stripped_text = text.rstrip()
print(f"|{right_stripped_text}|") # Output: '| Hello, World!|'
이러한 메서드는 표시 또는 처리를 위해 사용자 입력을 정리하거나 텍스트 서식을 지정하는 데 유용합니다. 공백뿐만 아니라 탭(\t) 및 개행 문자(\n)와 같은 다른 공백 문자도 제거합니다.
반응형