Python은 다양한 문자열 함수를 제공하여 문자열을 다루고 처리하는 데 유용하다. 이 글에서는 Python의 몇 가지 유용한 문자열 함수에 대해 알아본다.
len()
: 문자열 길이 구하기
len()
함수는 문자열의 길이를 반환한다. 문자열의 길이는 문자의 개수를 나타낸다.
text = "Hello, World!"
length = len(text)
print("문자열 길이:", length)
문자열 길이: 13
str.lower()
및 str.upper()
: 대소문자 변환
str.lower()
함수는 문자열을 모두 소문자로 변환하고, str.upper()
함수는 문자열을 모두 대문자로 변환한다.
text = "Hello, World!"
lower_text = text.lower()
print("소문자:", lower_text)
upper_text = text.upper()
print("대문자:", upper_text)
소문자: hello, world!대문자: HELLO, WORLD!
str.strip()
: 문자열 양쪽 공백 제거
str.strip()
함수는 문자열 양쪽 끝에 있는 공백을 제거한다.
text = " Hello, World! "
stripped_text = text.strip()
print("제거 전:", text)
print("제거 후:", stripped_text)
제거 전: Hello, World!
제거 후: Hello, World!
str.split()
: 문자열 분할
str.split()
함수는 문자열을 특정 구분자를 기준으로 분할하여 리스트로 반환한다. 구분자를 지정하지 않으면 공백을 기준으로 분할된다.
text = "apple,banana,cherry"
fruits = text.split(",")
print("분할 결과:", fruits)
분할 결과: ['apple', 'banana', 'cherry']
str.replace()
: 문자열 치환
str.replace()
함수는 문자열 내의 특정 부분을 다른 문자열로 치환한다.
text = "Hello, World!"
new_text = text.replace("World", "Python")
print("치환 전:", text)
print("치환 후:", new_text)
치환 전: Hello, World! 치환 후: Hello, Python!
str.startswith()
및 str.endswith()
: 접두사 및 접미사 확인
str.startswith()
함수는 문자열이 특정 접두사로 시작하는지 확인하고, str.endswith()
함수는 문자열이 특정 접미사로 끝나는지 확인한다.
text = "Hello, World!"
startsWithHello = text.startswith("Hello")
endsWithWorld = text.endswith("World")
print("시작 여부:", startsWithHello)
print("끝 여부:", endsWithWorld)
시작 여부: True
끝 여부: False
str.find()
및 str.index()
: 문자열 위치 찾기
str.find()
함수는 문자열 내에서 특정 부분 문자열의 첫 번째 발생 위치를 반환하며, 해당 부분 문자열이 없을 경우 -1을 반환한다. str.index()
함수도 비슷하게 작동하지만, 부분 문자열이 없을 경우 오류를 발생시킨다.
text = "Hello, World!"
position1 = text.find("World")
position2 = text.find("Python")
print("World 위치:", position1)
print("Python 위치:", position2)
World 위치: 7
Python 위치: -1