Computer Science/Python

[파이썬] String startswith(), 어떤 문자열로 시작하는지 확인

inee0727 2022. 8. 8. 18:09

startswith()를 이용하여 문자열이 특정 문자열로 시작하는지 확인할 수 있다.

1. 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

2. startswith()와 split()으로 단어가 특정 문자열로 시작하는지 확인

만약 어떤 문자열이 포함하고 있는 단어들 중에, 특정 문자열로 시작하는지 확인할 수도 있다.

다음과 같이 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!']

3. Comprehension과 startswith()로 단어가 특정 문자열로 시작하는지 확인

위에서 구현한 예제를 다음과 같이 list comprehension으로 간단히 구현할 수 있다.

list = [word for word in strings if word.startswith('Python')]
print(list)

 

 

https://codechacha.com/ko/python-find-something-starts-with-string/