python中文字符串检测子串是否存在

首先要明白python3中字符串分为两种,一种是str,另一种是bytes;前者采用unicode编码,后者是二进制。
我使用的是python3.7.2,在使用中发现创建的字符串变量默认为str

>>> type('abc')
<class 'str'>
>>> type(b'abc')
<class 'bytes'>
>>> type(u'abc')
<class 'str'>

在使用中文时必须使用str,从报错提示中可以看到,bytes只能包含ASCII的字符。

>>> type(u'中国')
<class 'str'>
>>> type(b'中国')
  File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> type('中国')
<class 'str'>

在字符串中检测子串可以采用str.find(sub, beg=0, end=len(string))方法。此方法检测字符串str中是否包含子字符串 sub ,如果指定beg(开始) 和end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1

if(str.find(sub)!=-1):
	do something
else:
	do something

strsub得同时是strbytes,不能两种混合,如果两者不一样就会报错,解决方案是用encode()str转为bytes或用decode()bytes转为str

>>> a=u'abc'
>>> b=b'abc'
>>> a.find(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not bytes
>>> b=b.decode()
>>> a.find(b)
0

>>> a=u'abc'
>>> b=b'abc'
>>> b.find(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument should be integer or bytes-like object, not 'str'
>>> a=a.encode()
>>> b.find(a)
0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值