Python 字符串方法

Python str.startswith() 方法用于判断字符串是否以指定前缀开头

语法

s.startswith(prefix, start=0, end=len(s))

参数

prefix:前缀字符串或前缀元组。可选 start/end:检查范围。

返回值

返回布尔值:以指定前缀开头为 True。

示例

print("hello.py".startswith("hello"))   # True
print("hello.py".startswith("py"))      # False
print("hello.py".endswith(".py"))       # True

url = "https://online-compiler.com"
if url.startswith("https"):
    print("安全连接")

files = ["a.py", "b.py", "c.txt"]
py = [f for f in files if f.endswith(".py")]
print(py)   # ['a.py', 'b.py']

输出:

True
False
True
安全连接
['a.py', 'b.py']

注意事项

prefix 可以是元组:s.startswith(("http:", "https:")) 匹配任一。endswith 同理。