startswith()
를 이용하여 문자열이 특정 문자열로 시작하는지 확인할 수 있습니다.
특정 문자열로 시작하는지 확인
예를 들어 다음과 같이 'Hello world, Python!'
가 Hello
로 시작하는지 확인할 수 있습니다.
str = 'Hello world, Python!'
if str.startswith('Hello'):
print('It starts with Hello')
if not str.startswith('Python'):
print('It does not start with Python')
Output:
It starts with Hello
It does not start with Python
만약 대소문자를 구분하지 않고 비교를 하고 싶다면 lower()
로 소문자로 변경 후, 소문자로 비교할 수 있습니다.
str = 'Hello world, Python!'
if str.lower().startswith('hello'):
print('It starts with hello')
Output:
It starts with hello
문자열의 단어가 특정 문자열로 시작하는지 확인
만약 어떤 문자열이 포함하고 있는 단어들 중에, 특정 문자열로 시작하는지 확인할 수도 있습니다.
다음과 같이 split()
으로 whitespace 단위로 단어들을 분리하고, 각각의 단어들에 대해서 startswith()
로 특정 단어로 시작하는지 확인할 수 있습니다.
str = 'Hello world, Python!'
strings = str.split()
list = []
for word in strings:
if word.startswith('Python'):
list.append(word)
print(list)
Output:
['Python!']
list comprehension으로 구현
위에서 구현한 예제를 다음과 같이 list comprehension으로 간단히 구현할 수 있습니다.
list = [word for word in strings if word.startswith('Python')]
print(list)
Recommended Posts:
- Python - dict 정렬 (Key, Value로 sorting)
- Python - String을 bytes로 변경하는 방법
- Python - bytes를 String으로 변환하는 방법
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 문자열에서 특정 단어 추출
- Python - float을 int로 변경하는 방법
- Python - dictionary의 중복 제거 방법
- Python - 리스트가 비어있는지 확인
- Python - 문자열 뒤집기, 문자열 거꾸로 출력
- Python - 현재 날짜, 시간 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트 크기(size) 구하기
- Python - 2차원 리스트를 1차원 리스트로 만들기