Python——第二章:查找和判断

查找.find()

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 判断是否不存在

看下面这个案例:

即便多次出现了world词,但程序只查到第一次就结束了,仅会返回7

text = "Hello, world! This is a test.world! world! world! "
index = text.find("world")    # 查找子字符串world
print(index)     # 只输出: 7

因此,想实现多次查找,就写个循环

text = "Hello, world! This is a world test.world!world!world!"

start = 0

while True:
    index = text.find("world", start)
    if index == -1:
        break
    print(f"Found 'world' at index {index}")
    start = index + 1

结果输出

Found 'world' at index 7
Found 'world' at index 24
Found 'world' at index 35
Found 'world' at index 41
Found 'world' at index 47

判断

判断开头和结尾:.startswith().endswith()

name = input("请输入你的名字:")
# 判断你是不是姓张
if name.startswith("张"):  # 判断字符串是否以xxxxx开头, endswith()
    print("你姓张")
else:
    print("不姓张")

判断整数:.isdigit()

isdigit() 是字符串方法之一,用于检查字符串是否只包含数字字符。如果字符串中所有字符都是数字字符(从0 到 9),则返回 True;否则,返回 False

string1 = "12345"
string2 = "42.5"
string3 = "Python123"

print(string1.isdigit())  # 输出: True
print(string2.isdigit())  # 输出: False
print(string3.isdigit())  # 输出: False
在示例中,
string1 只包含数字字符,所以 string1.isdigit() 返回 True
string2 包含了小数点,因此不是纯数字,所以 string2.isdigit() 返回 False
string3 包含字母字符,所以也不是纯数字,string3.isdigit() 也返回 False

.isdigit() 方法通常用于验证用户输入是否为整数或数字,因为它可以帮助你快速检查字符串是否满足特定的格式要求。

 

查询字符串长度:len     => length长度

s = "hello"
print(len(s))  # 结果:5

len与int、float、bool一样是python的内置函数

posted @   Magiclala  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-09-01 安装Zabbix客户端zabbix-agent2
2022-09-01 查看进程、端口号
点击右上角即可分享
微信分享提示