一、startsWith() 和 endsWith() 方法簡介
startsWith() 和 endsWith() 方法是 Python 字元串的兩個常用方法之一,它們分別用於判斷一個字元串是否以指定的前綴或後綴開始或結束。
startsWith() 方法接受一個參數,即要匹配的前綴。這個方法會比較原始字元串和要匹配的前綴,判斷原始字元串是否以該前綴開始。
str.startswith(prefix[, start[, end]])
其中,start 和 end 可選,表示開始和結束匹配的索引位置。
endsWith() 方法與 startsWith() 方法非常相似,它接受一個要匹配的後綴參數。它比較原始字元串和要匹配的後綴,判斷原始字元串是否以該後綴結束。
str.endswith(suffix[, start[, end]])
其中,start 和 end 可選,表示開始和結束匹配的索引位置。
二、startsWith() 和 endsWith() 方法的用法
startsWith() 和 endsWith() 方法的主要用法是在字元串匹配中。這些方法可以幫助我們判斷字元串是否以一段指定的前綴或後綴開始或結束。
以下是 startsWith() 方法的示例代碼:
str1 = "Python is easy to learn." print(str1.startswith('Python')) # True print(str1.startswith('is', 7, 9)) # True print(str1.startswith('easy', 10)) # False
上述代碼中,通過 startsWith() 方法分別判斷字元串 str1 是否以 Python、is 和 easy 開始。
endsWith() 方法的使用方法與 startsWith() 方法極其相似,以下是一段 endsWith() 方法的示例代碼:
str2 = "Python is easy to learn." print(str2.endswith('learn.')) # True print(str2.endswith('easy', 7, 11)) # True print(str2.endswith('Python', 0, 6)) # False
上述代碼中,通過 endsWith() 方法分別判斷字元串 str2 是否以 learn.、easy 和 Python 結尾。
三、startsWith() 和 endsWith() 方法的應用場景
startsWith() 和 endsWith() 方法可以應用於多種場景。例如,可以用它們來判斷一個 URL 是否以 http 或 https 開頭,在文件讀取中判斷文件擴展名是否為指定類型等。
以下是 startsWith() 方法的一個應用場景示例:
url = "https://www.example.com" if url.startswith('https://'): print('This is a secure URL')
上述代碼中,開始判斷 url 是否以 https:// 開頭。如果是,則輸出 「This is a secure URL」。
以下是 endsWith() 方法的一個應用場景示例:
file_name = 'example.txt' if file_name.endswith('.txt'): print('This is a text file')
上述代碼中,判斷 file_name 是否以 .txt 結尾。如果是,則輸出 「This is a text file」。
四、總結
startsWith() 和 endsWith() 方法是 Python 字元串處理中的兩個常用方法。它們通過比較字元串以判斷是否以指定前綴或後綴開始或結束。在應對多種場景時,這兩個方法可以幫助我們簡化代碼的編寫和匹配操作。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/183999.html