检查字符串是否以XXXX开头

本文翻译自: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

See the docs . 请参阅文档


#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')更好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值