Python Tekstonderdeel

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 String Substring

Latenn we eerst kijken naar twee verschillende manieren om een ​​substring te maken.

Maak een Substring

We kunnen een substring maken met behulp van string slicing. We kunnen de split()-functie gebruiken om een ​​lijst van substrings te maken op basis van de opgegeven delimiter.

s = 'My Name is Pankaj'

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

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

Output:

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

Controleren of substring is gevonden

We kunnen de in-operator of de find()-functie gebruiken om te controleren of de substring aanwezig is in de string of niet.

s = 'My Name is Pankaj'

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

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

Merk op dat de find()-functie de indexpositie van de substring retourneert als deze wordt gevonden, anders retourneert deze -1.

Aantal keren dat een substring voorkomt

We kunnen de count() functie gebruiken om het aantal keren dat een substring voorkomt in een string te vinden.

s = 'My Name is Pankaj'

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

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

Uitvoer:

Substring count = 3
Substring count = 3

Vind alle indexen van de substring

Er is geen ingebouwde functie om de lijst van alle indexen voor de substring te krijgen. We kunnen er echter gemakkelijk een definiëren met behulp van de find() functie.

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'))

Uitvoer: [0, 8, 17]

Je kunt het volledige Python-script en meer Python-voorbeelden bekijken op onze GitHub Repository.

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