Python 文字列のサブ文字列

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の文字列の部分文字列

まず、部分文字列を作成する2つの異なる方法を見てみましょう。

部分文字列の作成

文字列スライスを使用して、部分文字列を作成することができます。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]

Pythonの完全なスクリプトや他のPythonの例は、GitHubリポジトリからご覧いただけます。

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