Check if a string starts with a specific string in Python
This post will discuss how to check if a string starts with a specific string in Python.
1. Using str.startswith() function
The preferred, fast way to check if the string starts with the given prefix uses the str.startswith() function.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = "Techie" word = "Tech" res = s.startswith(word) print(res) # True |
The str.startswith() function can also accept a tuple of prefixes. This is useful when you want to match multiple prefixes with the string.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = "Techie" word = ("T", "S") res = s.startswith(word) print(res) # True |
2. Using Regex
Another approach is to use the regex, but using a regex match for this trivial task would be overkill. This is demonstrated below in Python:
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = "Techie" res = re.match(r'^Tech', s) is not None print(res) # True |
That’s all about determining whether a string starts with a specific string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)