I would like to know how to check whether a string starts with "hello" in Python.
In Bash I usually do:
if [[ "$string" =~ ^hello ]]; then
do something here
fi
How do I achieve the same in Python?
RanRag
aString = "hello world"
aString.startswith("hello")
More info about startwith
Shawabawa
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.
user1767754
In case you want to match multiple words to your magic word you can pass the words to match as a tuple:
>>> magicWord = 'zzzTest'
>>> magicWord.startswith(('zzz', 'yyy', 'rrr'))
True
Note: startswith
takes str or a tuple of str
See the docs.
Can also be done this way..
regex=re.compile('^hello')
## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')
if re.match(regex, somestring):
print("Yes")
来源:https://stackoverflow.com/questions/8802860/checking-whether-a-string-starts-with-xxxx