문자열 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)
'Python > [개념 및 문법]' 카테고리의 다른 글
[python] 2차원 배열 선언과 활용 (0) | 2023.07.14 |
---|---|
[python] 문자열 찾기, 문자열의 특정 위치 찾기_ index, find 함수 (0) | 2023.07.04 |
[python] 문자열 추가하기, 연결하기_join함수 (0) | 2023.07.04 |
[python] 주어진 숫자들 중 최댓값, 최솟값 구하기 구현 (0) | 2023.07.02 |
[python] 특정 원소의 개수 세기 cnt, count (0) | 2023.06.30 |