Python/[개념 및 문법]

[python] 특정 문자열이 있는지 찾기_slicing, for 문 이용

hyunnn_00 2023. 7. 4. 10:27
문자열 s에 특정 문자열 'ab'가 포함되어 있는지 여부 확인하기
s = 'appleabanana'
length = len(s)
exists = False

for i in range(length - 1):
    if s[i] == 'a' and s[i + 1] == 'b':
        exists = True

print(exists)

 

slicing 이용하기
s = 'appleabanana'
length = len(s)
exists = False

for i in range(length - 1):
    if s[i:i + 2] == 'ab':
        exists = True

print(exists)

 

in 키워드 사용하기
s = 'appleabanana'
print('ab' in s)

만약 판단하고자 하는 부분문자열이 input으로 주어진다면?

문자열 t의 길이를 len_t라 했을 때, 결국 s[i]와 t[0], s[i + 1]과 t[1] ...그리고 s[i + len_t - 1]과 t[len_t - 1]이 전부 일치하기를 바라는 것이기 때문에 이 역시도 bool 값을 만들어 전부 일치하는지에 대한 여부를 판단해주면 됨

#  i 01234567891011
s = 'appleabanana'
t = 'abbaba'

n = len(s)
exists = False

len_t = len(t)

for i in range(n - len_t + 1):
    all_same = True
    for j in range(len_t):
        if s[i + j] != t[j]:
            all_same = False
    
    #if s[i] == t[0] and s[i + 1] == t[1] and ....
    #    s[i + len_t - 1] == t[len_t - 1]:
    if all_same == True:
        exists = True

print(exists)