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](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2021/07/Python-string-starts-with-regex.jpg?resize=446%2C142&ssl=1)
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.