Start and end string match

This blog explain string matching text at the start or end

We may want to perform string matching at the start or end of the string.

This can be done to match for specific file extension such as .txt, .py or url matching

There are two method for matching start or end text in the string

str.startswith()
str.endswith()

Below code has two lines. In the first line, filename variable is initialized with value ‘test.txt’. In the second line, endswith() method is use to check whether string in filename ends with ‘.txt’. Returns true when text matches

filename = 'test.txt'
print(filename.endswith('.txt'))

Output

True
filename = 'test.txt'
print(filename.startswith('test'))

Output

True
filename = 'test.txt'
print(filename.startswith('file'))

Output

False

Text matching can also be done for url

url = 'https://www.w3schools.com/python/ref_string_split.asp'
print(url.endswith('.asp'))

Output

True
url = 'https://www.w3schools.com/python/ref_string_split.asp'
print(url.startswith('http'))

Output

True
url = 'https://www.w3schools.com/python/ref_string_split.asp'
print(url.startswith('www'))

Output

False

Below example find number of files ends with ‘.txt’ and also share name of those file

filename = ['test.txt','test1.py','test2.bin','test3.xls','test4.txt']
counter = 0
textfile = []

for file in filename:
    if file.endswith('.txt'):
        counter = counter + 1
        textfile.append(file)
print('Number of text file:',counter)
print('Name of text files: ',textfile)

Output

Number of text file: 2
Name of text files:  ['test.txt', 'test4.txt']
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s