59doit

[Python] 문자열 관련함수 본문

Programming/Python(파이썬)

[Python] 문자열 관련함수

yul_S2 2022. 10. 26. 20:54
반응형

count : 찾는 문자의 개수 출력

a = "happy"
a.count('p')
# <출력> 2

 

find() : 찾는 문자가 몇번째 자리에 있는지

★없으면 -1로 출력된다

a = "python is the best choice"
a.find('e')  # <출력> 12
a.find('c')  # <출력> 19
a.find('j')  # <출력> -1

 

index() : 찾는 문자가 몇번째 자리에 있는지

★없으면 Error

a="life is too short"
a.index('o')  #<출력> 9
a.index('j')  #<출력> ValueError: substring not found

 

 

문자열 삽입

기본과 리스트or튜플 응용하기

",".join('abc')          #<출력>'a,b,c'
",".join(['a','b','c'])  #<출력>'a,b,c'

 

upper() : 대문자로바꾸기

lower() : 소문자로바꾸기

a="hello"
a.upper()    #<출력> 'HELLO'

a="Hello"
a.lower()    #<출력> 'hello'

 

 

rstrip() : 오른쪽 공백지우기

lstrip() : 왼쪽 공백지우기

strip() : 양쪽 공백지우기

a=" hehe      "
a.rstrip()      #<출력> ' hehe'

b="  hehe  "
b.lstrip()      #<출력> 'hehe  '

c="  he he    "
c.strip()       #<출력> 'he he'

 

 

 

replace() : 문자열 바꾸기 

relace(old, new)

- old : 현재 문자열에서 변경하고 싶은 문자
- new: 새로 바꿀 문자

a="life is too short"
a.replace("life","your leg")
#<출력> 'your leg is too short'

 

 

split() : 문자열 나누기 

a="life is too short"
a.split( )     # 공백기준으로 나누기

b="life:is:too:short"
b.split(':')   # : 기준으로 나누기

 

 

반응형

'Programming > Python(파이썬)' 카테고리의 다른 글

[Python] tuple, set, dic  (0) 2022.10.27
[Python] 리스트  (0) 2022.10.27
[Python] 포맷팅 format  (0) 2022.10.25
[Python] 인덱싱 index(),find()  (0) 2022.10.24
[Python] 인덱싱, 연산, 슬라이싱  (0) 2022.10.23
Comments