Please enable java script to visit.
NOTEBOOK
HOMEPHP / MySQLJS / HTMLWXappPythonC++Blender其他
Python 判断字符串里是否存在某些字符串 in/not in/find()/index() / endswith() / startswith() - NOTEBOOK
Python 判断字符串里是否存在某些字符串 in/not in/find()/index() / endswith() / startswith()
Python
Posted on 2023-05-15
摘要 : find() 方法与 index() 方法几乎相同,查找指定值的首次出现, 如果找不到该值 find() 方法返回 -1。唯一的区别是,如果找不到该值,index() 方法将引发异常。
❱ in/not in

a = 'str'
b = 'hers is a string data'
if a in b :
print('yes')

#yes



❱ find() 方法与 index() 方法几乎相同

❱ 查找指定值的首次出现, 如果找不到该值 find() 方法返回 -1。唯一的区别是,如果找不到该值,index() 方法将引发异常。

txt = "Hello, welcome to my world."
print( txt.find("welcome") )
print( txt.find("TO") )

#7
#-1


❱ index() 找不到时出错

txt = "Hello, welcome to my world."
print( txt.index("welcome") )
print( txt.index("TO") )

#7
#ValueError: substring not found



❱ string.startswith(value, start, end)

value 必需。检查字符串是否以其开头的值。
start 可选。整数,规定从哪个位置开始搜索。
end 可选。整数,规定结束搜索的位置。
txt = "Hello, welcome to my world."
x = txt.startswith("Hello")
print(x)
# true

# 检查位置 7 到 20 是否以字符 "wel" 开头:
txt = "Hello, welcome to my world."
x = txt.startswith("wel", 7, 20)
print(x)
# true



❱ string.endswith(value, start, end)

txt = "Hello, welcome to my world."
x = txt.endswith("my world.")
print(x)
# true

#检查位置 5 至 11 是否以短语 "my world." 结尾:
txt = "Hello, welcome to my world."
x = txt.endswith("my world.", 5, 11)
print(x)
# false