Python String startswith()

Python string.startswith() checks the start of a string for specific text patterns e.g. URL schemes and so on. It returns True if a string starts with the specified prefix. If not, it returns False.

message = 'Welcome to Python Programming!'

print(message.startswith('Welcome'))     #True
print(message.startswith('Hello'))       #False

1. Syntax

The syntax for using Python startswith() method is as follows. The method can take 3 arguments and return either True or False.

str.startswith(prefix[, start[, end]])
  • prefix (mandatory) – String or tuple of strings to be checked.
  • start (optional) – Beginning position where prefix is to be checked within the string. If not specified, the method searches from the beginning of the string.
  • end (optional) – Ending position where prefix is to be checked within the string. If not specified, the method searches till the end of the string.
message = 'Welcome to Python Programming!'

print(message.startswith('Welcome'))	#True
print(message.startswith('Welcome', 0))	#True
print(message.startswith('Python', 11))	#True
print(message.startswith('Python', 11, 20))	#True

print(message.startswith('Hello'))		#False

2. String startswith() with Tuples

If we need to check against multiple prefixes then we can provide a tuple of strings to startswith().

filenames = ["temp.txt", "test.ppt", "hello.doc", "world.xls"]

for name in filenames:
    if name.startswith(('temp', 'test')):
        print(name)

The program output.

temp.txt
test.ppt

3. String startswith() with List or Set

To use startswith(), tuple is a required as input. If we want to use a list or set, just make sure we convert them using tuple() first.

filenames = ["temp.txt", "test.ppt", "hello.doc", "world.xls"]
fileNameFilters = ['temp', 'test']

for name in filenames:

    #TypeError: startswith first arg must be str or a tuple of str, not list
    #if name.startswith(fileNameFilters):

    if name.startswith(tuple(fileNameFilters)):
        print(name)

The program output.

temp.txt
test.ppt

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode