[파이썬]문자열 내부 함수(for 코테)

이윤성·2022년 3월 23일
0

코테 준비 중, '문자열 때문에 파이썬으로 왔다'라는 말이 있을 만큼 파이썬에서는 문자열에 대해 유용한 기능이 많다.
그렇지만 자주 써먹지 않으면 잊어버려 이참에 정리를 했다.

  • 특정 문자 개수 세기
    • count()
    a = "hello"
    # 1
    a.count("h")
    # 2
    a.count("l")
  • 특정 문자 위치
    • find()
    a = "hello"
    # 2 -> 문자가 여러개인 경우 find,index는 모두 맨 앞의 위치를 가져온다.
    a.find('l')
    # 0
    a.find('h')
    • index()
    find와 index의 차이는 찾는 문자가 없을 때 결과이다.
    find는 -1 index는 오류가 발생한다.
    하지만 index는 리스트, 튜플에서도 사용 가능
  • 문자열 합치기
    • join()
    a = ['h','e','l','l','o']
    # 'hello'
    ''.join(a)
    # 'h,e,l,l,o'
    ','.join(a)
  • 소문자 -> 대문자
    • upper()
    a = "helLo"
    # HELLO
    a.upper()
    # helLo
    print(a)
  • 대문자 -> 소문자
    • lower()
    a = "helLo"
    # hello
    a.upper()
    # helLo
    print(a)
  • 공백 지우기
    • lstrip()
    a = "    hello"
    # "hello"
    a.lstrip()
    # "    hello"
    print(a)
    • rstrip()
    a = "hello    "
    # "hello"
    a.rstrip()
    # "hello    "
    print(a)
    • strip()
    a = "   hello    "
    # "hello"
    a.strip()
    # "   hello    "
    print(a)
  • 특정 문자를 기준으로 자르기
    • split()
    a = "hello"
    # ['he', '', 'o']
    a.split('l')

0개의 댓글

관련 채용 정보