군침이 싹 도는 코딩

STRINGS - 문자열을 다루는 함수 2 (len,strip,find,count,start/endswith) 본문

Python

STRINGS - 문자열을 다루는 함수 2 (len,strip,find,count,start/endswith)

mugoori 2022. 12. 26. 10:41

문자열의 길이를 알아보거나 특정 문자를 제거할수있다.(  len , strip  )

letters
>>> 'abcdefghijklmnopqrstuvwxyz'

len(letters) # len 함수를 사용하며 파라미터안에 변수명을 입력해주면
>>> 26       # 해당 변수에 들어있는 문자열의 갯수를 알려준다
email
>>> 'hello@naver.com'

email.strip('h') # 스트립 안에 파라미터에 제거하고 싶은 문자열을 넣으면 제거된다
>>> 'ello@naver.com'

 

 

 

문자열의 위치를 찾을수있다. (  find , rfind  )

print(poem)
>>> So "it is" quite different, then, if in a mountain town
    the mountains are close, rather than far. Here

    they are far, their distance away established,
    consistent year to year, like a parent’s

    or sibling’s. They have their own music.
    So I confess I do not know what it’s like,

    listening to mountains up close, like a lover,
    the silence of them known, not guessed at.
    
# year 단어를 찾아보자
poem.find('year') # find를 사용하면 문자열에서 인덱스를 찾아준다
>>> 162

poem.rfind('year') # rfind를 사용하면 오른쪽을 기준으로 찾아준다
>>> 170

poem.find('banana') # 없는 단어는 -1로 나온다 0이 아닌 이유는 0은 인덱스로 사용중이기 때문이다
>>> -1

 

 

 

 

문자열의 갯수를 파악할수 있다 (  count  )

print(poem)
>>> So "it is" quite different, then, if in a mountain town
    the mountains are close, rather than far. Here

    they are far, their distance away established,
    consistent year to year, like a parent’s

    or sibling’s. They have their own music.
    So I confess I do not know what it’s like,

    listening to mountains up close, like a lover,
    the silence of them known, not guessed at.
        
poem.count('year') # count 함수를 사용하며 파라미터안에
>>> 2              # 문자를 넣으면 해당문자가 몇개인지 세어준다

poem.count('banana')
>>> 0

'year' in poem # in은 앞에 있는 단어가 변수안에 있는지 물어볼때 사용한다
>>> True

'banana' not in poem # not 을 붙인 not in 도 사용할 수 있다
>>> True

 

 

 

 

시작 문자열이나 끝 문자열을 확인 할수있다. (  startswith / endswith  )

text = '안녕하세요? 오늘 날씨가 좋네요.'

text.startswith('안녕') # startswith 함수는 첫 시작이 무엇인지 물어보는 함수이다.
>>> True                # bool 로 출력해준다

text.endswith('하세요.') # endswith 함수는 마지막이 무엇인지 물어보는 함수이다.
>>> False                # bool 로 출력해준다