一、Pythonendwith怎麼用
Python中的endwith()函數是用來判斷一個字元串是否以某個子字元串結尾的函數。
它的基本語法如下:
str.endswith(suffix, start, end)
其中,suffix表示要檢查的結尾字元串,start和end表示可選參數,表示要檢查的起始位置和結束位置。
下面是一個簡單的例子:
str = "Hello world"
if str.endswith("world"):
print("字元串以world結尾")
else:
print("字元串不以world結尾")
運行結果:
字元串以world結尾
二、Pythonendwith函數用法選取
1. 檢查文件類型
在文件操作中,我們經常需要判斷一個文件是否以某種特定的文件類型結尾,比如是否以「.jpg」、「.png」等。這時,我們可以使用endwith函數來判斷:
filename = "example.jpg"
if filename.endswith(".jpg"):
print("文件是jpg類型")
else:
print("文件不是jpg類型")
2. 檢查URL鏈接
在爬蟲編程中,我們需要檢查網址URL是否以特定的鏈接結尾,比如」.html」、「.php」等,這時,我們可以使用endwith函數來判斷:
url = "https://www.example.com/article/123.html"
if url.endswith(".html"):
print("URL鏈接是html格式")
else:
print("URL鏈接不是html格式")
3. 檢查無關鍵字
有些時候,我們需要從一堆字元串中篩選出不符合某個特定條件的字元串,比如不以某個關鍵字結尾的字元串。這時,我們就可以使用endwith函數來判斷:
strings = ["test", "example.py", "hello-world"]
for s in strings:
if not s.endswith(".py"):
print("不是Python文件:" + s)
4. 獲取文件後綴名
在文件操作中,我們經常需要獲取文件的後綴名,這時,我們可以使用split()函數和endwith()函數來實現:
filename = "example.jpg"
suffix = filename.split(".")[-1]
if suffix.endswith("jpg"):
print("文件是jpg類型")
else:
print("文件不是jpg類型")
5. 檢查郵箱域名
在郵件發送和接收中,我們需要檢查郵箱的域名是否屬於特定的公司或機構,比如檢查是否為「@example.com」的郵箱的域名是否以「.com」結尾。這時,我們可以使用endwith函數來判斷:
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")
原創文章,作者:EWWI,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/137726.html