Python/포스팅

파이썬 문자열 관련 함수

짜집퍼박사(짜박) 2023. 12. 2. 14:10

파이썬에서는 문자열을 다루기 위한 다양한 내장 함수들이 있습니다. 아래는 몇 가지 주요한 문자열 관련 함수들에 대한 설명입니다.

 

1. len(): 문자열의 길이 반환

text = "Hello, World!"
length = len(text)  # 결과: 13

 

2. str(): 다른 자료형을 문자열로 변환

number = 42
text_number = str(number)  # 결과: '42'

 

3. lower(): 문자열의 모든 문자를 소문자로 변환

text = "Hello, World!"
lower_text = text.lower()  # 결과: 'hello, world!'

 

4. upper(): 문자열의 모든 문자를 대문자로 변환

text = "Hello, World!"
upper_text = text.upper()  # 결과: 'HELLO, WORLD!'

 

5. capitalize(): 문자열의 첫 글자를 대문자로 변환

text = "hello, world!"
capitalized_text = text.capitalize()  # 결과: 'Hello, world!'

 

6. title(): 각 단어의 첫 글자를 대문자로 변환

text = "hello world"
title_text = text.title()  # 결과: 'Hello World'

 

7. count(): 특정 부분 문자열의 출현 횟수 반환

text = "Hello, Hello, Hello"
count_hello = text.count("Hello")  # 결과: 3

 

8. find(): 특정 부분 문자열의 첫 번째 인덱스 반환 (없으면 -1)

text = "Hello, World!"
index_hello = text.find("Hello")  # 결과: 0
index_python = text.find("Python")  # 결과: -1

 

9. replace(): 특정 부분 문자열을 다른 문자열로 대체

text = "Hello, World!"
new_text = text.replace("World", "Python")  # 결과: 'Hello, Python!'

 

10. split(): 문자열을 특정 구분자로 나누어 리스트 반환

text = "apple,orange,banana"
fruits = text.split(",")  # 결과: ['apple', 'orange', 'banana']

 

11. strip(), lstrip(), rstrip(): 문자열 양쪽, 왼쪽, 오른쪽 공백 제거

text = "   Hello, World!   "
stripped_text = text.strip()  # 결과: 'Hello, World!'
left_stripped_text = text.lstrip()  # 결과: 'Hello, World!   '
right_stripped_text = text.rstrip()  # 결과: '   Hello, World!'

이러한 문자열 관련 함수들은 다양한 작업을 수행할 수 있도록 도와줍니다. 특히 문자열 처리는 다양한 프로그래밍 작업에서 중요한 부분이므로 이러한 함수들을 잘 이해하고 활용하는 것이 중요합니다.

 

With ChatGPT

'Python > 포스팅' 카테고리의 다른 글

파이썬 리스트 인덱싱  (0) 2023.12.02
파이썬 리스트 자료형  (0) 2023.12.02
파이썬 f 문자열 포매팅  (0) 2023.12.02
파이썬 format 함수를 사용한 포매팅  (0) 2023.12.02
파이썬 문자열 포맷 코드  (0) 2023.12.02