本文翻译自:Checking whether a string starts with XXXX
I would like to know how to check whether a string starts with "hello" in Python. 我想知道如何检查Python中字符串是否以“ hello”开头。
In Bash I usually do: 在Bash中,我通常这样做:
if [[ "$string" =~ ^hello ]]; then
do something here
fi
How do I achieve the same in Python? 如何在Python中实现相同的目标?
#1楼
参考:https://stackoom.com/question/aw1c/检查字符串是否以XXXX开头
#2楼
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")
#3楼
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
注意 : startswith
需要str or a tuple of str
#4楼
aString = "hello world"
aString.startswith("hello")
More info about startwith 有关startwith的更多信息
#5楼
RanRag has already answered it for your specific question. RanRag已经回答了您的特定问题。
However, more generally, what you are doing with 但是,更一般地说,您在做什么
if [[ "$string" =~ ^hello ]]
is a regex match. 是正则表达式匹配。 To do the same in Python, you would do: 要在Python中执行相同的操作,您可以执行以下操作:
import re
if re.match(r'^hello', somestring):
# do stuff
Obviously, in this case, somestring.startswith('hello')
is better. 显然,在这种情况下, somestring.startswith('hello')
更好。