[python] string의 몰랐던 내장 메소드들

한승수·2024년 12월 5일

AI 코딩 팁

목록 보기
4/11

이런저런 코드들을 보다가 string을 길이에 맞춰 앞에 0을 채워주는 string 내장함수 zfill를 발견하였다! 항상 파일 이름을 저장하거나, 불러올 때 이 숫자들 앞에 있는 0을 어떻게 처리해야 하나 고민이 많았고, 함수를 하나 만들어서 사용하곤 했는데 이런 메소드가 원래 있었다니!!! 뭔가 상당히 배신당한 느낌이다...
한번 배신당한 김에 오늘 몰아서 배신당하기로 했다. 지금까지 코딩하면서 유용하게 활용했던 문자열 메소드와 앞으로 유용하게 쓰일 문자열 메소드를 정리해봅니다.

1. 문자열 조작

  • str.upper() / str.lower(): 대문자/소문자로 변환
  • str.strip([chars]): 문자열의 양쪽 공백/지정 문자 제거
  • str.replace(old, new, [count]): 문자열 내 특정 패턴 대체
    예제
title = ' hello python '
print(title.upper()) #[ HELLO PYTHON ]
print(title.strip()) #[hello python]
print(title.replace('python','world')) #[ hello world ]

2. 문자열 검사

  • str.isalpha(): 알파벳인지 확인
  • str.isdigit(): 숫자인지 확인
  • str.isalnum(): 알파벳+숫자인지 확인
  • str.startswith(prefix) / str.endswith(suffix): 특정 문자열로 시작/끝나는지 확인
title = 'hello_python'
print(title.isalpha()) #False: _가 포함되어 있음 'hellopython'은 True
print(title.isdigit()) #False
print(title.isalnum()) #False
print(title.startswith('h')) #True
print(title.endswith('s')) #False

3. 서식 지정

  • str.zfill(width): 문자열을 0으로 채워서 지정된 길이로 만듦
    예제
yearmonth=[]
for i in range(2022,2023):
    for m in range(12):
        im = str(i+1)+str(m+1).zfill(2)
        print(im)

출력결과

202301
202302
202303
202304
202305
202306
202307
202308
202309
202310
202311
202312

4. 분리와 결합

  • str.split([sep], [maxsplit]): 구분자를 기준으로 분리하여 리스트 반환
  • str.partition(sep): 문자열을 3부분으로 나눔 (왼쪽, 구분자, 오른쪽)
  • str.join(iterable): 문자열을 기준으로 iterable의 요소를 결합
title = 'hello_python_me'
print(title.split('_')) #['hello', 'python', 'me']
print(title.split('_',1)) #['hello', 'python_me'] #1을 지정해 첫번째 '_'만 split
print(title.partition('_')) #('hello', '_', 'python_me')

arr = ['hello','_','python']
print(''.join(arr)) #hello_python
print(', '.join(arr)) #hello, _, python #결합 시에도 결합인자를 추가할 수 있다.

conclusion

오늘은 간단하지만 많이 활용하지 않다보면 놓칠 수 있는 꿀 문자열 메소드들에 대해 알아봤습니다. 앞으로 코딩할 때 효율적으로 할 수 있도록 많이 애용 해야겠습니다.

profile
Grooovy._.Han

0개의 댓글