HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Python / Python string startswith() example

Python string startswith() example

Python string.startswith() method is used to check the start of a string for specific text patterns e.g. URL schemes and so on.

1. String startswith() example

A simple python program to check the beginning a string is to use the String.startswith().

>>> url = 'https://howtodoinjava.com'

>>> url.startswith('https:')

True		#Output

>>> url.startswith('http:')

False		#Output

2. String startswith() with tuples

If you need to check against multiple choices, simply provide a tuple of strings to startswith().

>>> filenames = ["temp.txt", "temp.ppt", "temp.doc", "temp.xls"]

>>> [name for name in filenames if name.endswith(('.doc', '.ppt')) ]

['temp.ppt', 'temp.doc']		#Output

>>> any( name.endswith('.txt') for name in filenames )

True							#Output

3. String startswith() with list or set

To use startswith(), tuple is actually required as input. If you happen to have the choices specified in a list or set, just make sure you convert them using tuple() first.

For example:

>>> choices = ['https:', 'http:', 'ftp:']

>>> url = 'https://howtodoinjava.com'

>>> url.startswith(choices)		#ERROR !! TypeError: startswith first arg must be str, unicode, or tuple, not list

>>> url.startswith( tuple(choices) )	#Correct

True							#Output

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Python Inbuilt Functions

  • Python abs()
  • Python all()
  • Python any()
  • Python ascii()
  • Python bin()
  • Python input()
  • Python print()

Python String Functions

  • Python String endswith()
  • Python String split()
  • Python String startswith()

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces