aString = "hello world"
aString.startswith("hello")
More info about startswith.
aString = "hello world"
aString.startswith("hello")
More info about startswith.
RanRag has already answered it for your specific question.
However, more generally, what you are doing with
if [[ "$string" =~ ^hello ]]
is a regex match. To do the same in Python, you would do:
import re
if re.match(r'^hello', somestring):
# do stuff
Obviously, in this case, somestring.startswith('hello') is better.
What does startswith() do in Python?
Is Python startswith() case-sensitive?
What is the difference between startswith() and in?
Series.str.startswith does not 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 (as explained in the docs):
df.col1.str.contains('^[Cc]ountry')
The character class [Cc] is probably a better way to match C or c than (C|c), unless of course you need to capture which letter is used. In this case you can do ([Cc]).
Series.str.startswith does not accept regexes. Use Series.str.match instead:
df.col1.str.match(r'(C|c)ountry', as_indexer=True)
Output:
0 True
1 True
Name: col1, dtype: bool
How about not using a regular expression at all?
if string.startswith("ftp://") and string.endswith(".jpg"):
Don't you think this reads nicer?
You can also support multiple options for start and end:
if (string.startswith(("ftp://", "http://")) and
string.endswith((".jpg", ".png"))):
re.match will match the string at the beginning, in contrast to re.search:
re.match(r'(ftp|http)://.*\.(jpg|png)$', s)
Two things to note here:
r''is used for the string literal to make it trivial to have backslashes inside the regexstringis a standard module, so I chosesas a variable- If you use a regex more than once, you can use
r = re.compile(...)to built the state machine once and then user.match(s)afterwards to match the strings
If you want, you can also use the urlparse module to parse the URL for you (though you still need to extract the extension):
>>> allowed_schemes = ('http', 'ftp')
>>> allowed_exts = ('png', 'jpg')
>>> from urlparse import urlparse
>>> url = urlparse("ftp://www.somewhere.com/over/the/rainbow/image.jpg")
>>> url.scheme in allowed_schemes
True
>>> url.path.rsplit('.', 1)[1] in allowed_exts
True