문자열에 특정 문자열 포함하는지 확인하는 방법을 소개합니다.

1. ‘in’ 키워드로 문자열 포함 여부 확인

'ABC' in str은 문자열 ABC가 문자열 str 안에 있을 때 true를 리턴합니다.

not inin의 부정으로, 특정 문자열이 존재하지 않을 때 true를 리턴합니다.

str = "Hello world, python"

if "world" in str:
    print("Found world")

if "java" not in str:
    print("Not found java")

Output:

Found world
Not found java

2. find()로 문자열 포함 여부 확인

str.find('ABC')는 문자열에 ABC가 있을 때 ABC의 Index를 리턴합니다. 만약 ABC라는 문자열이 안에 없으면 -1을 리턴합니다. 즉, 리턴 값이 -1이 아니면 문자열 안에 특정 문자열이 포함되어 있다고 확인할 수 있습니다.

반대로 find()의 리턴 값이 -1이면 특정 문자열이 존재하지 않는다고 확인할 수 있습니다.

str = "Hello world, python"

print(str.find("Hello"))
print(str.find("world"))
print(str.find("java"))

if str.find("java") == -1:
    print("No java")

if str.find("python") != -1:
    print("Found python")

Output:

0
6
-1
No java
Found python