Python中的endswith()函數是一個非常有用的字符串方法,它用于檢查一個字符串是否以指定的后綴結尾。該函數的語法如下:
str.endswith(suffix[, start[, end]])
_x000D_其中,suffix是要檢查的后綴,start和end是可選參數,用于指定字符串的起始和結束位置。如果字符串以指定的后綴結尾,則該函數返回True,否則返回False。
_x000D_例如,以下代碼將檢查一個字符串是否以“world”結尾:
_x000D_ _x000D_str = "Hello, world!"
_x000D_if str.endswith("world"):
_x000D_print("The string ends with 'world'")
_x000D_else:
_x000D_print("The string does not end with 'world'")
_x000D_ _x000D_輸出結果為:
_x000D_ _x000D_The string ends with 'world'
_x000D_ _x000D_我們將探討endswith()函數的更多用法,并回答一些與該函數相關的常見問題。
_x000D_## 如何檢查多個后綴?
_x000D_有時候我們需要檢查一個字符串是否以多個后綴中的任意一個結尾。這時,我們可以將多個后綴放在一個元組中,然后將該元組作為endswith()函數的參數。例如:
_x000D_ _x000D_str = "file"
_x000D_if str.endswith(("", ".pdf", ".doc")):
_x000D_print("The file is a text document")
_x000D_else:
_x000D_print("The file is not a text document")
_x000D_ _x000D_輸出結果為:
_x000D_ _x000D_The file is a text document
_x000D_ _x000D_## 如何忽略大小寫?
_x000D_endswith()函數默認是區分大小寫的,但有時候我們需要忽略大小寫。這時,我們可以將字符串轉換為小寫或大寫,然后再調用endswith()函數。例如:
_x000D_ _x000D_str = "Hello, World!"
_x000D_if str.lower().endswith("world"):
_x000D_print("The string ends with 'world'")
_x000D_else:
_x000D_print("The string does not end with 'world'")
_x000D_ _x000D_輸出結果為:
_x000D_ _x000D_The string ends with 'world'
_x000D_ _x000D_## 如何指定起始和結束位置?
_x000D_endswith()函數可以接受兩個可選參數,用于指定字符串的起始和結束位置。例如:
_x000D_ _x000D_str = "Hello, world!"
_x000D_if str.endswith("world", 7):
_x000D_print("The string ends with 'world'")
_x000D_else:
_x000D_print("The string does not end with 'world'")
_x000D_ _x000D_輸出結果為:
_x000D_ _x000D_The string ends with 'world'
_x000D_ _x000D_在上面的代碼中,第二個參數7表示從字符串的第7個字符開始檢查。
_x000D_## 如何檢查空字符串?
_x000D_如果我們想檢查一個字符串是否以空字符串結尾,可以將空字符串作為endswith()函數的參數。例如:
_x000D_ _x000D_str = "Hello, world!"
_x000D_if str.endswith(""):
_x000D_print("The string ends with an empty string")
_x000D_else:
_x000D_print("The string does not end with an empty string")
_x000D_ _x000D_輸出結果為:
_x000D_ _x000D_The string ends with an empty string
_x000D_ _x000D_## 如何檢查多行字符串?
_x000D_如果我們有一個多行字符串,如何檢查每一行是否以指定的后綴結尾?一種方法是使用splitlines()函數將字符串分割成多行,然后使用for循環遍歷每一行。例如:
_x000D_ _x000D_str = """Hello, world!
_x000D_How are you today?
_x000D_I hope you are doing well."""
_x000D_suffix = "day?"
_x000D_for line in str.splitlines():
_x000D_if line.endswith(suffix):
_x000D_print(line)
_x000D_ _x000D_輸出結果為:
_x000D_ _x000D_How are you today?
_x000D_ _x000D_在上面的代碼中,我們使用splitlines()函數將字符串分割成多行,并使用for循環遍歷每一行。然后,我們使用endswith()函數檢查每一行是否以指定的后綴結尾。
_x000D_##
_x000D_endswith()函數是Python中一個非常有用的字符串方法,它可以用于檢查一個字符串是否以指定的后綴結尾。除了基本用法之外,我們還可以使用endswith()函數檢查多個后綴、忽略大小寫、指定起始和結束位置、檢查空字符串以及檢查多行字符串。掌握這些技巧,可以讓我們更加靈活地處理字符串。
_x000D_