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.
How can I match the start and end in Python's regex? - Stack Overflow
Python - regex search for string which starts and ends with the given text - Stack Overflow
Regex for all words starting with "Con" or "con" in file
How to remove string that start with "\*" and end with "*\" in python
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
The problem is that your pattern matches any string that comes after by test_ and before .py, but that doesn't restrict it from having other characters before the test_ or after the .py.
You need to use start (^) and end ($) anchors. Also, don't forget to escape the . character. Try this pattern:
(?<=^test_).+(?=\.py$)
Look at this:
import re
files = [
"test_1.py",
"Test.py",
"test.pyc",
"test.py",
"script.py"]
print [x for x in files if re.search("^test_.*py$", x)]
output:
['test_1.py']