首先要明白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
str
和sub
得同时是str
或bytes
,不能两种混合,如果两者不一样就会报错,解决方案是用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