Python的查找和判断
查找
s = "你好啊. 我叫周润发"
ret = s.find("周润发") # 返回是7,代表该字符串出现在7号位置,从0开始计数
print(ret)
ret2 = s.find("周润发12312") # 返回是-1就是没有该字符串出现
print(ret2)
ret3 = s.index("周润发12312") # 报错就是没有
print(ret3)
print("周润发" in s) # in可以做条件上的判断
print("周润发" not in s) # not in 判断是否不存在
判断
判断开头和结尾:.startswith()
和 .endswith()
name = input("请输入你的名字:")
# 判断你是不是姓张
if name.startswith("张"): # 判断字符串是否以xxxxx开头, endswith()
print("你姓张")
else:
print("不姓张")
判断整数:.isdigit()
money = input("请输入你都里的钱:")
if money.isdigit(): # 判断字符串是否由整数组成.
money = int(money)
print("可以花钱了")
else:
print("对不起,您输入有误....")
查询字符串长度:len => length长度
s = "hello"
print(len(s)) # 结果:5
len与int、float、bool一样是python的内置函数