s = "Zhao min is very beautiful and Zou kexin is very fascinating"
s1 = "Zhao min"
# 返回第一次发现这个字符串的位置
s.find(s1)
s2 = "zhu rui"
# 返回-1表示没有找到
s.find(s2)
-1
help(str.find)
Help on method_descriptor:
find(...)
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
help(str.index)
Help on method_descriptor:
index(...)
S.index(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
# index 会报错或者引发异常
s.index(s2)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
1 # index 会报错或者引发异常
----> 2 s.index(s2)
ValueError: substring not found
# 使用的时候还可以使用区间
s = "Zhao min is very beautiful and Zou kexin is very fascinating"
s1 = "Zhao min"
#从下标20开始查找,看能否找到了
s.find(s1,20)
-1
此类函数的特点是一般都用is开头,比如islower
isalpha:判断是否是字母,需要注意的是两点:
isdigit,isnumeric,isdecimal三个判断数字的函数
- 此类函数不建议使用,在后期爬虫中,判断是否是数字建议采用正则表达式的方式
digit()
True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
False: 汉字数字
Error: 无
isdecimal()
True: Unicode数字,,全角数字(双字节)
False: 罗马数字,汉字数字
Error: byte数字(单字节)
isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 无
Error: byte数字(单字节)
islower:判断字符串是大写或小写
# 以下三个都不是的,因为有除了字以外的空格等
s1 = "我们对着灯发誓,敏儿是最美的"
s2 = "little min is friend of mine"
s3 = "Zhao min is 1.st"
print(s1.isalpha())
print(s2.isalpha())
print(s3.isalpha())
False
False
False
# 需要注意的是,因为输入法的问题,输入罗马数字可能得不到我们想要的结果
chin_num = "一二三四"
print(chin_num.isdigit())
print(chin_num.isnumeric())
print(chin_num.isdecimal())
False
True
False
miner = "Zhao min"
zhurui = "Zhu rui"
s = "Zhao min really love Zhu rui"
print(s.startswith(miner))
print(s.endswith(zhurui))
True
True
s1 = "Zhao min is beautiful"
s2 = "Zhaominisbeautiful"
s3 = "zhaominisbeautiful"
# s4包含空格,但空格不影响结果,忽略
s4 = "Zhao min is verybeautiful"
s5 = "敏儿是最美的"
print(s1.islower())
print(s2.islower())
print(s3.islower())
print(s4.islower())
print(s5.islower())
print(s5.isupper())# 汉字字符串无大小写
False
False
True
False
False
False
c = "XXXXXxiao min is fascinating "
# 是否成功删除两边空格不能观察出来
print(c.strip(),end = "--------")
print()
print(c.strip("X"),end = "--------")
XXXXXxiao min is fascinating--------
xiao min is fascinating --------
#join 的例子,需要把s1,s2,s3,作为分隔符,把ss内的内容拼接在一起
s1 = "$"
s2 = "-"
s3 = " "
ss = ["i","love","you","so","much"]
print(s1.join(ss))
print(s2.join(ss))
print(s3.join(ss))
i$love$you$so$much
i-love-you-so-much
i love you so much