检查字符串是否以XXXX开头

2024-03-28 23:09:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在Bash中,我通常会:

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

如何在Python中实现相同的功能?


Tags: 字符串功能bashhellostringifheredo
3条回答

如果您想将多个单词匹配到您的神奇单词,您可以将要匹配的单词作为元组传递:

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

注意startswith接受str or a tuple of str

请参阅docs

RanRag has already answered这是你的具体问题。

然而,更一般地说,你在做什么

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

是一个regex匹配项。要在Python中执行同样的操作,您可以执行以下操作:

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

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

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

有关startwith的详细信息

相关问题 更多 >