Skip to content

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading