1 Python startswith() 与 endswith 描述

startswith() 方法 : 用于判断字符串是否以指定后缀开头,如果以指定后缀开头返回True,否则返回False

endswith() 方法 : 用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False

2 demo 说明

2.1 startswith

2.1.1 匹配成功的情况

str_content = "Python"  # 要匹配的内容
str_pattern = "P"  # 判断的条件
start_content = str_content.startswith(str_pattern)
print(start_content)
if start_content:
    print("是以指定内容开头")
else:
    print("不是以指定内容开头")

打印结果:

python 匹配字符串 python 匹配字符串尾_Python

2.2.1 匹配失败的情况

str_content = "Python"  # 要匹配的内容
str_pattern = "y"  # 判断的条件
start_content = str_content.startswith(str_pattern)
print(start_content)
if start_content:
    print("是以指定内容开头")
else:
    print("不是以指定内容开头")

打印结果:

python 匹配字符串 python 匹配字符串尾_Python_02

2.2 endswith

2.2.1 匹配成功的情况:

str_content = "Python"  # 要匹配的内容
str_pattern = "n"  # 判断的条件
start_content = str_content.endswith(str_pattern)
print(start_content)
if start_content:
    print("是以指定内容开头")
else:
    print("不是以指定内容开头")

打印结果:

python 匹配字符串 python 匹配字符串尾_后缀_03

2.2.2 匹配失败的情况

str_content = "Python"  # 要匹配的内容
str_pattern = "N"  # 判断的条件
start_content = str_content.endswith(str_pattern)
print(start_content)
if start_content:
    print("是以指定内容开头")
else:
    print("不是以指定内容开头")

打印结果:

python 匹配字符串 python 匹配字符串尾_字符串_04

总结 : 匹配是区分大小写的