습관처럼

python - string(2) 본문

Language/python

python - string(2)

dev.wookii 2019. 12. 22. 01:22

문자열 관련 함수들

 

count: 개수


>>> a = "hobby"
>>> a.count('b')
2

find: 문자를 통해 인덱스 위치

 


>>> a = "Python is the best choice"
>>> a.find('b')
14
>>> a.find('k')
-1

 

 

index: 인덱스 위치


>>> a = "Life is too short"
>>> a.index('t')
8
>>> a.index('k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found

join: 문자열 사이에 해당문자를 삽입


>>> ",".join('abcd') #abcd 문자열의 각각의 문자 사이에 ','를 삽입한다.
'a,b,c,d'

upper: 전부 대문자로


>>> a = "hi"
>>> a.upper()
'HI'

lower: 전부 소문자로


>>> a = "HI"
>>> a.lower()
'hi'

lstrip: 왼쪽 공백 제거


>>> a = " hi "
>>> a.lstrip()
'hi '

rstrip: 오른쪽 공백 제거


>>> a= " hi "
>>> a.rstrip()
' hi'

strip: 양쪽 공백 제거


>>> a = " hi "
>>> a.strip()
'hi'

replace: 문자열 대체


>>> a = "Life is too short"
>>> a.replace("Life", "Your leg")
'Your leg is too short'

split: 공백을 기준으로 문자열 나누기


>>> a = "Life is too short"
>>> a.split()
['Life', 'is', 'too', 'short']
>>> b = "a:b:c:d"
>>> b.split(':')
['a', 'b', 'c', 'd']

출처:https://wikidocs.net/13

'Language > python' 카테고리의 다른 글

python - 정규식을 이용한 문자열 검색  (0) 2019.12.22
python - regex(정규표현식)  (0) 2019.12.22
python - string(1)  (0) 2019.12.22
python - lambda  (0) 2019.12.22
python - 내장함수  (0) 2019.12.22