파이썬 문자열 부분 문자열

A substring is the part of a string. Python string provides various methods to create a substring, check if it contains a substring, index of substring etc. In this tutorial, we will look into various operations related to substrings.

Python 문자열 하위 문자열

먼저 부분 문자열을 만드는 두 가지 다른 방법을 살펴보겠습니다.

부분 문자열 만들기

우리는 문자열 슬라이싱을 사용하여 부분 문자열을 만들 수 있습니다. 우리는 split() 함수를 사용하여 지정된 구분자를 기반으로 부분 문자열의 목록을 만들 수 있습니다.

s = 'My Name is Pankaj'

# create substring using slice
name = s[11:]
print(name)

# list of substrings using split
l1 = s.split()
print(l1)

출력:

Pankaj
['My', 'Name', 'is', 'Pankaj']

부분 문자열이 있는지 확인하기

부분 문자열이 문자열에 있는지 여부를 확인하기 위해 in 연산자나 find() 함수를 사용할 수 있습니다.

s = 'My Name is Pankaj'

if 'Name' in s:
    print('Substring found')

if s.find('Name') != -1:
    print('Substring found')

find() 함수는 부분 문자열이 발견되면 해당 위치의 인덱스를 반환하고, 그렇지 않으면 -1을 반환합니다.

부분 문자열 발생 횟수 세기

우리는 문자열 내의 부분 문자열 발생 횟수를 찾기 위해 count() 함수를 사용할 수 있습니다.

s = 'My Name is Pankaj'

print('Substring count =', s.count('a'))

s = 'This Is The Best Theorem'
print('Substring count =', s.count('Th'))

출력:

Substring count = 3
Substring count = 3

부분 문자열의 모든 인덱스 찾기

부분 문자열에 대한 모든 인덱스 목록을 얻는 데 내장 함수가 없습니다. 그러나 find() 함수를 사용하여 쉽게 정의할 수 있습니다.

def find_all_indexes(input_str, substring):
    l2 = []
    length = len(input_str)
    index = 0
    while index < length:
        i = input_str.find(substring, index)
        if i == -1:
            return l2
        l2.append(i)
        index = i + 1
    return l2


s = 'This Is The Best Theorem'
print(find_all_indexes(s, 'Th'))

출력: [0, 8, 17]

완전한 파이썬 스크립트와 더 많은 파이썬 예제는 GitHub 저장소에서 확인할 수 있습니다.

Source:
https://www.digitalocean.com/community/tutorials/python-string-substring