问题:检查字符串是否以XXXX开头

我想知道如何检查Python中字符串是否以“ hello”开头。

在Bash中,我通常这样做:

if [[ "$string" =~ ^hello ]]; then
 do something here
fi

如何在Python中实现相同的目标?

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?


回答 0

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

有关的更多信息startswith

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

More info about startswith.


回答 1

RanRag已经回答了您的特定问题。

但是,更一般地说,您在做什么

if [[ "$string" =~ ^hello ]]

正则表达式匹配。要在Python中执行相同的操作,您可以执行以下操作:

import re
if re.match(r'^hello', somestring):
    # do stuff

显然,在这种情况下somestring.startswith('hello')更好。

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.


回答 2

如果您想将多个单词与魔术单词匹配,则可以将单词匹配为元组:

>>> magicWord = 'zzzTest'
>>> magicWord.startswith(('zzz', 'yyy', 'rrr'))
True

注意startswithstr or a tuple of str

请参阅文档

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.


回答 3

也可以这样

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")

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")

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。