Python string starts with regex | Example code

Series.str.startswith doesn’t accept regex because it is intended to behave similarly to str.startswith in vanilla Python, which does not accept regex. The alternative is to use a regex match.

 re.match(pattern, string)

Use Series.str.match instead Python string starts with regex

Simple python example code using the re.match(pattern, string) function from the re module.

import re

some_str = "Hello world"

if re.match(r'^Hello', some_str):
    print("Given String start with 'Hello'")

Output:

Python string starts with regex

Obviously, in this case, somestring.startswith('hello') is better.

See which of these methods

These are most efficient to return whether a certain string begins with another string.

  • string.startswith('hello')
  • string.rfind('hello') == 0
  • string.rpartition('hello')[0] == ''
  • string.rindex('hello') == 0

Do comment if you have any doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.