【小白从小学Python、C、Java】
【Python全国计算机等级考试】
【Python数据分析考试必会题】
● 标题与摘要
Python判断字符串是否以指定后缀结尾
endswith()方法
● 选择题
请问以下Python代码输出的结果是什么?
A = "china"
suffix="ina"
print(A.endswith(suffix))
print(A.endswith(suffix,0,3))
A True True
B True False
C False False
D False True
● 问题解析
1. 语法:
str.endswith(suffix,start,end),suffix为指定的后缀,start字符串中的开始位置,end字符串中的结束位置。在start和end构成的范围内,若字符串是以指定后缀suffix结尾,则返回True;否则返回False。
2. 题目解析:
A.endswith(suffix),字符串为"china",指定的后缀为"ina",字符串是以指定后缀结尾,所以返回True。
A.endswith(suffix,0,3),指定范围的字符串为"chin",指定的后缀为"ina",在指定范围内不是以指定后缀结尾,所以返回False。
● 附图
● 附图代码
A = "china"
suffix="ina"
print(A.endswith(suffix))
print(A.endswith(suffix,0,3))
● 正确答案
B