본문 바로가기
Python/문법

[Python] 파이썬에서 자주 사용되는 문자열 함수들

by 에파 2024. 7. 25.
728x90

파이썬에는 문자열 처리를 쉽게 할 수 있는 강력한 내장 함수들을 제공합니다. 이 글에서는 그러한 함수들을 소개하고, 각 함수의 사용법과 예제를 설명하겠습니다.

 

1. 'len()': 문자열 길이 구하기

'len()' 함수는 문자열의 길이를 반환합니다.

 

text = "Hello, World!"
length = len(text)
print(length)

# 출력 결과
# 13

 

2. 'str.lower()': 소문자로 변환

'lower()' 함수는 문자열을 소문자로 변환합니다.

 

text = "Hello, World!"
lower_text = text.lower()
print(lower_text)

# 출력 결과
# hello, world!

 

3. 'str.upper()': 대문자로 변환

'upper()' 함수는 문자열을 대문자로 변환합니다.

 

text = "Hello, World!"
upper_text = text.upper()
print(upper_text)

# 출력 결과
# HELLO, WORLD!

 

4. 'str.strip()': 공백 제거

'strip()' 함수는 문자열의 양쪽 끝에 있는 공백을 제거합니다. 'lstrip()'은 왼쪽 끝의 공백만, 'rstrip()'은 오른쪽 끝의 공백만 제거합니다.

 

text = "   Hello, World!   "
stripped_text = text.strip()
print(f"'{stripped_text}'")

# 출력 결과
# 'Hello, World!'

 

5. 'str.replace()': 문자열 대체

'replace()' 함수는 문자열 내의 특정 부분을 다른 문자열로 대체합니다.

 

text = "Hello, World!"
replaced_text = text.replace("World", "Python")
print(replaced_text)

# 출력 결과
# Hello, Python!

 

6. 'str.split()': 문자열 분리

'split()' 함수는 문자열을 특정 구분자를 기준으로 분리하여 리스트로 반환합니다. 기본 구분자는 공백입니다.

 

text = "Hello, World!"
words = text.split()
print(words)

# 출력 결과
# ['Hello,', 'World!']

 

구분자를 지정할 수도 있습니다.

 

text = "apple,banana,cherry"
fruits = text.split(',')
print(fruits)

# 출력 결과
# ['apple', 'banana', 'cherry']

 

7. 'str.join()': 문자열 합치기

'join()' 함수는 리스트 등의 반복 가능한 객체의 요소들을 하나의 문자열로 합칩니다.

 

words = ["Hello", "World"]
sentence = " ".join(words)
print(sentence)

# 출력 결과
# Hello World

 

8. 'str.find()': 문자열 찾기

'find()' 함수는 특정 문자열이 처음으로 나타나는 위치를 반환합니다. 찾는 문자열이 없으면 '-1'을 반환합니다.

 

text = "Hello, World!"
position = text.find("World")
print(position)

# 출력 결과
# 7

 

9. 'str.startswith()', 'str.endswith()': 접두사/접미사 검사

'startswith()' 함수는 문자열이 특정 접두사로 시작하는지 검사하고, 'endswith()' 함수는 특정 접미사로 끝나는지 검사합니다.

 

text = "Hello, World!"
print(text.startswith("Hello"))  # True
print(text.endswith("World!"))  # True

 

10. 'str.isdigit()', 'str.isalpha()': 숫자/알파벳 검사

'isdigit()' 함수는 문자열이 모두 숫자로 이루어져 있는지 검사하고, 'isalpha()' 함수는 문자열이 모두 알파벳 문자로 이루어져 있는지 검사합니다.

 

text1 = "12345"
text2 = "Hello"
print(text1.isdigit())  # True
print(text2.isalpha())  # True

 

 

 

이 글에서는 파이썬에서 자주 사용되는 문자열 함수들을 소개했습니다. 이 함수들을 잘 활용하면 문자열 처리 작업을 효율적으로 수행할 수 있습니다.

 

댓글