Checking whether a string starts with XXXX

徘徊边缘 提交于 2019-11-26 02:18:24

问题


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?


回答1:


aString = "hello world"
aString.startswith("hello")

More info about startwith




回答2:


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.




回答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

See the docs.




回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!