Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 문자열에 하위 문자열이 있는지 확인

<시간/>

파이썬 데이터 분석에서 우리는 주어진 부분 문자열이 더 큰 문자열의 일부인지 확인하는 시나리오를 접할 수 있습니다. 우리는 다음 프로그램을 통해 이를 달성할 것입니다.

찾기 기능

find 함수는 지정된 값의 첫 번째 항목을 찾습니다. 값을 찾지 못하면 -1을 반환합니다. 우리는 이 함수를 주어진 문자열에 적용하고 부분 문자열이 문자열의 일부인지 알아내기 위한 if 절을 디자인할 것입니다.

Astring = "In cloud 9"
Asub_str = "cloud"
# Given string and substring
print("Given string: ",Astring)
print("Given substring: ",Asub_str)
if (Astring.find(Asub_str) == -1):
   print("Substring is not a part of the string")
else:
   print("Substring is part of the string")

# Check Agian
Asub_str = "19"
print("Given substring: ",Asub_str)
if (Astring.find(Asub_str) == -1):
   print("Substring is not a part of the string")
else:
   print("Substring is part of the string")

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given string: In cloud 9
Given substring: cloud
Substring is part of the string
Given substring: 19
Substring is not a part of the string

카운트 포함

count() 메서드는 파이썬에서 문자열이나 데이터 컬렉션에서 지정된 값을 가진 요소의 수를 반환합니다. 아래 프로그램에서 우리는 부분 문자열의 개수를 계산할 것이고 그것이 0보다 크면 우리는 부분 문자열이 더 큰 문자열에 존재한다는 결론을 내릴 것입니다.

Astring = "In cloud 9"
Asub_str = "cloud"
# Given string and substring
print("Given string: ",Astring)
print("Given substring: ",Asub_str)
if (Asub_str.count(Astring)>0):
   print("Substring is part of the string")
else:
   print("Substring is not a part of the string")

# Check Agian
Asub_str = "19"
print("Given substring: ",Asub_str)
if (Asub_str.count(Astring)>0):
   print("Substring is a part of the string")
else:
   print("Substring is not a part of the string")

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given string: In cloud 9
Given substring: cloud
Substring is not a part of the string
Given substring: 19
Substring is not a part of the string