본문 바로가기

사전학습 Python

7.문자열 메서드

내장함수

Ex. len() 문자열 길이를 반환


text = "www.GOOGLE.com"

print(len(text))

#14


메서드

메서드는 참조연산자(.)을 사용한다.

 

capitalize()

첫글자 대문자로 변환


text = "www.GOOGLE.com"

text_capitalize = text.capitalize()
print(text_capitalize) 

#Www.google.com


 

 

upper()

문자열 전체를 대문자로 변환

lower()

문자열 전체를 소문자로 변경


text_upper = text.upper()

print(text_upper)

#WWW.GOOGLE.COM"

 

text_lower = text.lower()

print(text_lower)

#ww.google.com


 

 

count()

요소를 찾아서 세어줌


g_cnt = text.count('G') 
print(g_cnt) 

#2


 

 

find()

요소의 위치를 반환. (존재하지 않으면 -1을 반환)


g_find = text.find('G')
print(g_find) 

#4

g_find = text.find('G' , 5)

#두번째 G인 5반환


 

 

index() 

요소의 위치를 반환 (존재하지 않으면 ValueError)


g_idx = text.index('G')
print(g_idx) 

#4


 

 

replace() 

문자열 치환


text_naver = text.replace("GOOGLE", "NAVER")
print(text_naver) 

#www.NAVER.com


 

 

 

split()

요소(기본은 공백)를 기준으로 문자열을 분리


print(text.split('.')) 

#['www', 'GOOGLE', 'com']


 

 

strip()

문자열 맨앞과 맨끝의 공백을 삭제


text2 = "        www.GOOGLE.com"
stp = text2.strip()
print(stp) 

# www.GOOGLE.com


 

'사전학습 Python' 카테고리의 다른 글

9. 2차원 리스트  (0) 2023.03.14
8.List 리스트  (0) 2023.03.14
6. 포메팅  (0) 2023.03.12
5. 문자열 인덱싱, 슬라이싱  (0) 2023.03.12
4. 산술, 비교, 논리 연산자  (0) 2023.03.05