01_Python

14_자료형>문자열 관련 함수

chuu_travel 2025. 1. 3. 01:11
728x90
문자열 관련 함수

 

str1 = "hobby"

 

# 문자 개수 세기
str1.count("b")

 

<실행 결과>

2

 

# 검색하는 문자가 존재하지 않는 경우 -1 반환
str1.find("a")

 

<실행 결과>

-1

 

# 위치 찾기2
str1.index("b")

 

<실행 결과>

2

 

 

# 검색하는 문자가 존재하지 않는 경우 에러 발생
str1.index("a")

 

<실행 결과>

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[70], line 2
      1 # 검색하는 문자가 존재하지 않는 경우 에러 발생
----> 2 str1.index("a")

ValueError: substring not found

 

# 대소문자 변환
print("hello".upper())
print("HELLO".lower())

<실행 결과>

HELLO
hello

 

# 공백 제거(양쪽 끝 공백만 제거)
" hel lo ".strip()

<실행 결과>

'hel lo'

 

 

# 문자열 치환
str1 = "pithon"

str1.replace("i", "y")

 

<실행 결과>

'python'

 

 

# 문자열 나누기
str1 = "Life is too short"

str1.split()

 

<실행 결과>

['Life', 'is', 'too', 'short']

 

 

str2 = "a:b:c:d"

str2.split(":")

 

<실행 결과>

['a', 'b', 'c', 'd']

 

 

# 문자열의 길이 구하기
print(len("안녕하세요"))

 

<실행 결과>

5

 

 

728x90