
목차
strip | split | join | endswith | lower | upper | startswith | replace
find | removesuffix | zfill | pop | isdigit | isupper | islower | swapcase()
lower() | upper() | capitalize() | title() |
.strip()
- 용도
- 문자열 양쪽 끝의 불필요한 공백(띄어쓰기, 줄바꿈 등)을 잘라냅니다.
- 기본적으로는 공백(띄어쓰기, 탭\t, 줄바꿈\n)을 제거하지만, 인자를 전달하여 특정 문자를 제거도 가능
- 실무 팁
- 사용자의 입력값(request.data)을 받을 때는 무조건 strip()을 한번 해주는게 좋음
strip(): 양쪽 끝 제거
lstrip() (Left Strip): 왼쪽(앞부분) 끝만 제거
rstrip() (Right Strip): 오른쪽(뒷부분) 끝만 제거
기본 사용
text = " Hello Python "
print(f"'{text.strip()}'")
print(f"'{text.lstrip()}'")
print(f"'{text.rstrip()}'")
심화 사용 (특정 문자 제거)
- strip에 문자열을 인자로 넣으면, 그 문자열에 포함된 모든 문자를 양쪽 끝에서 제거
- 인자로 "abc"를 주면, 정확히 "abc"라는 순서의 단어를 지우는 게 아니라
- 'a', 'b', 'c' 중 하나라도 양쪽 끝에 있으면 계속 지워 나갑니다.
text = "...,,!!Hello!!,,..."
clean_text = text.strip(".,!")
print(clean_text)
.split()
- 용도
- 특정 문자 기준으로 문자열을 조각내서 리스트(List)로 만들어줌
- 기본 사용법(
문자열.split())
- 괄호 안에 아무것도 안 넣으면 공백(스페이스바, 탭, 엔터)을 기준으로 자름
email = "contact@gmail.com"
parts = email.split("@")
print(parts)
sentence = "Hello World Python"
words = sentence.split()
print(words)
구분자 지정(문자열.split('구분자'))
- 콤마(,)나 콜론(:) 등 특정 문자를 기준으로 자를 수도 있음
data = "apple,banana,grape"
fruits = data.split(',')
print(fruits)
data = input().split()
print(data)
.join()
- 용도
- 리스트 안의 문자열들을 특정 접착제(구분자)로 이어 붙입니다.
"구분자".join(리스트/튜플/문자열이터러블)
- join()은 문자열만 연결 가능 → 숫자라면
map(str, 리스트)나 str() 변환 필요
- 리스트(혹은 튜플 등)에 있는 문자열들을 "구분자"를 사이에 넣어서 하나의 문자열로 합침
tags = ["Python", "Django", "DRF"]
tag_string = ", ".join(tags)
print(tag_string)
words = ["apple", "banana", "cherry"]
result = " ".join(words)
print(result)
result = ", ".join(words)
print(result)
result = "-".join(words)
print(result)
----------------------------------------------------
nums = [1, 2, 3, 4]
print(" + ".join(map(str, nums)))
----------------------------------------------------
.endswith()
filename = "report.pdf"
if filename.endswith((".png", ".jpg", ".jpeg")):
print("이미지 파일입니다.")
else:
print("이미지 파일이 아닙니다.")
lower() / .upper()
search_query = "DjAnGo"
db_data = "django"
if search_query.lower() == db_data.lower():
print("검색 결과 찾음!")
startswith
- 파이썬의 문자열(String) 객체가 가지고 있는 메서드
- 이름 그대로 "이 문자열이 특정 문구로 시작하는니?" 라고 물어보는 기능
- 결과는 항상 True(맞음) 또는 False(아님)로 나옴
사용 예시
text = "multipart/form-data"
print(text.startswith("multi"))
print(text.startswith("json"))
- startswith에는 튜플 ()을 넣어서 "이 중 하나라도 시작하면 통과"시킬 수도 있음
filename = "profile.jpg"
url = "https://naver.com"
if url.startswith(("http", "https")):
print("올바른 웹 주소입니다.")
replace
- 이름 그대로 문자열 안에 있는 "특정 글자를 찾아 다른 글자로 바꿔주는" 메서드
기본 사용법
text = "나는 사과를 좋아해. 사과는 맛있어."
new_text = text.replace("사과", "바나나")
print(new_text)
개수 제한하기
- 세 번째 자리에 숫자를 넣으면, "앞에서부터 딱 몇 개만 바꿔라"고 시킬 수도 있음
text = "apple, apple, apple"
print(text.replace("apple", "orange", 1))
주의
- 파이썬의 문자열은 '불변(Immutable)'
- replace를 썼다고 해서 원본 변수(text)가 바뀌는 게 아님
- 바뀐 새로운 문자열을 복사해서 돌려주는 것입니다. 그래서 반드시 변수에 다시 담아줘야 함
s = "Hello World"
s.replace("World", "Python")
print(s)
s = s.replace("World", "Python")
print(s)
혼합
- 앞뒤 공백 없애고 (strip) / 대문자로 통일하고 (upper) / 콤마로 쪼개기 (split)
raw_tags = " python, django, api "
clean_tags = raw_tags.strip().upper().split(", ")
print(clean_tags)
.isdigit()
- 용도
- 문자열이 '0~9'로만 이루어져 있는지 검사 (True/False)
order_id = "12345"
weird_id = "12a45"
print(order_id.isdigit())
print(weird_id.isdigit())
.find()
email = "admin@naver.com"
at_pos = email.find("@")
print(at_pos)
print(email.find("kakao"))
.removeprefix() / .removesuffix()
- 용도
- 앞에 붙은 특정 문구나 뒤에 붙은 확장자를 깔끔하게 잘라냅니다.
url = "https://www.google.com"
token = "Bearer abcde12345"
print(url.removeprefix("https://"))
print(token.removeprefix("Bearer "))
.zfill()
- 용도
- 전체 자릿수를 정하고, 빈 앞자리를 0(Zero)으로 채움(Fill).
number = "42"
formatted = number.zfill(5)
print(formatted)
.pop()
- 용도
- 꺼내서 확인하고 버리기
- 괄호 안에 아무것도 안 넣으면 맨 마지막(맨 오른쪽) 요소를 꺼냄
- 기본 사용법(
리스트.pop())
stack = [10, 20, 30]
item = stack.pop()
print(item)
print(stack)
인덱스 지정(리스트.pop(인덱스))
- 특정 위치의 것을 집어서 꺼낼 수도 있습니다.
fruits = ['사과', '바나나', '포도']
item = fruits.pop(0)
print(item)
print(fruits)
pop()
- (맨 뒤 꺼내기)은 속도가 매우 빠릅니다.
$O(1)$
pop(0)
- (맨 앞 꺼내기)은 꺼낸 뒤 뒤에 있는 애들을 다 한 칸씩 앞으로 당겨야 해서 느림
$O(N)$
isupper / islower
- 용도
- 문자열이나 개별 문자가 대문자인지 혹은 소문자인지 확인하는 전용 메서드
- Python의 str 객체는 상태를 확인하기 위한 직관적인 메서드를 제공
str.isupper()
- 문자열 내의 모든 알파벳이 대문자이고, 적어도 하나의 알파벳이 포함되어 있으면 True를 반환합니다.
str.islower()
- 문자열 내의 모든 알파벳이 소문자이고, 적어도 하나의 알파벳이 포함되어 있으면 True를 반환합니다.
내장 메서드 활용 (isupper, islower)
text = "Hello World123"
for char in text:
if char.isupper():
print(f"'{char}'는 대문자입니다.")
elif char.islower():
print(f"'{char}'는 소문자입니다.")
else:
print(f"'{char}'는 알파벳이 아닙니다.")
char = 'A'
if 65 <= ord(char) <= 90:
print("대문자입니다.")
elif 97 <= ord(char) <= 122:
print("소문자입니다.")
swapcase()
original = "PyThOn"
result = original.swapcase()
print(result)
upper() / lower() / capitalize() / title()
- 용도
upper() : 모든 문자를 대문자로
lower() : 모든 문자를 소문자로
capitalize() : 문자열의 맨 첫 글자만 대문자로 만들고 나머지는 소문자로 바꿉니다.
title() : 각 단어의 첫 글자를 대문자로 만듭니다.
text = "python 123"
print(text.upper())
text = "HELLO World"
print(text.lower())
``
``
``
``