Python中的endwith函数

发布时间:2023-05-19

一、Python endswith怎么用

Python中的endswith()函数是用来判断一个字符串是否以某个子字符串结尾的函数。 它的基本语法如下:

str.endswith(suffix, start, end)

其中,suffix表示要检查的结尾字符串,start和end表示可选参数,表示要检查的起始位置和结束位置。 下面是一个简单的例子:

str = "Hello world"
if str.endswith("world"):
    print("字符串以world结尾")
else:
    print("字符串不以world结尾")

运行结果:

字符串以world结尾

二、Python endswith函数用法选取

1. 检查文件类型

在文件操作中,我们经常需要判断一个文件是否以某种特定的文件类型结尾,比如是否以“.jpg”、“.png”等。这时,我们可以使用endswith函数来判断:

filename = "example.jpg"
if filename.endswith(".jpg"):
    print("文件是jpg类型")
else:
    print("文件不是jpg类型")

2. 检查URL链接

在爬虫编程中,我们需要检查网址URL是否以特定的链接结尾,比如”.html”、“.php”等,这时,我们可以使用endswith函数来判断:

url = "https://www.example.com/article/123.html"
if url.endswith(".html"):
    print("URL链接是html格式")
else:
    print("URL链接不是html格式")

3. 检查无关键字

有些时候,我们需要从一堆字符串中筛选出不符合某个特定条件的字符串,比如不以某个关键字结尾的字符串。这时,我们可以使用endswith函数来判断:

strings = ["test", "example.py", "hello-world"]
for s in strings:
    if not s.endswith(".py"):
        print("不是Python文件:" + s)

4. 获取文件后缀名

在文件操作中,我们经常需要获取文件的后缀名,这时,我们可以使用split()函数和endswith()函数来实现:

filename = "example.jpg"
suffix = filename.split(".")[-1]
if suffix.endswith("jpg"):
    print("文件是jpg类型")
else:
    print("文件不是jpg类型")

5. 检查邮箱域名

在邮件发送和接收中,我们需要检查邮箱的域名是否属于特定的公司或机构,比如检查是否为“@example.com”的邮箱的域名是否以“.com”结尾。这时,我们可以使用endswith函数来判断:

email = "example@example.com"
if email.split("@")[-1].endswith(".com"):
    print("邮箱域名为.com")
else:
    print("邮箱域名不为.com")

三、代码部分

str = "Hello world"
if str.endswith("world"):
    print("字符串以world结尾")
else:
    print("字符串不以world结尾")
filename = "example.jpg"
if filename.endswith(".jpg"):
    print("文件是jpg类型")
else:
    print("文件不是jpg类型")
url = "https://www.example.com/article/123.html"
if url.endswith(".html"):
    print("URL链接是html格式")
else:
    print("URL链接不是html格式")
strings = ["test", "example.py", "hello-world"]
for s in strings:
    if not s.endswith(".py"):
        print("不是Python文件:" + s)
filename = "example.jpg"
suffix = filename.split(".")[-1]
if suffix.endswith("jpg"):
    print("文件是jpg类型")
else:
    print("文件不是jpg类型")
email = "example@example.com"
if email.split("@")[-1].endswith(".com"):
    print("邮箱域名为.com")
else:
    print("邮箱域名不为.com")