Il metodoendswith () restituisce True se una stringa termina con il suffisso specificato. In caso contrario, restituisce False.
La sintassi di endswith()
è:
str.endswith (suffix (, start (, end)))
Endswith () Parametri
Il endswith()
prende tre parametri:
- suffix - Stringa o tupla di suffissi da controllare
- start (opzionale) - Posizione iniziale in cui controllare il suffisso all'interno della stringa.
- end (opzionale) - Posizione finale in cui il suffisso deve essere verificato all'interno della stringa.
Valore restituito daendswith ()
Il endswith()
metodo restituisce un valore booleano.
- Restituisce True se le stringhe terminano con il suffisso specificato.
- Restituisce False se la stringa non termina con il suffisso specificato.
Esempio 1 :endswith () Senza parametri di inizio e fine
text = "Python is easy to learn." result = text.endswith('to learn') # returns False print(result) result = text.endswith('to learn.') # returns True print(result) result = text.endswith('Python is easy to learn.') # returns True print(result)
Produzione
Falso vero vero
Esempio 2 :endswith () con i parametri di inizio e fine
text = "Python programming is easy to learn." # start parameter: 7 # "programming is easy to learn." string is searched result = text.endswith('learn.', 7) print(result) # Both start and end is provided # start: 7, end: 26 # "programming is easy" string is searched result = text.endswith('is', 7, 26) # Returns False print(result) result = text.endswith('easy', 7, 26) # returns True print(result)
Produzione
Vero Falso Vero
Passaggio di tupla aendswith ()
È possibile passare un suffisso di tupla al endswith()
metodo in Python.
Se la stringa termina con qualsiasi elemento della tupla, endswith()
restituisce True. In caso contrario, restituisce False
Esempio 3 :endswith () con suffisso di tupla
text = "programming is easy" result = text.endswith(('programming', 'python')) # prints False print(result) result = text.endswith(('python', 'easy', 'java')) #prints True print(result) # With start and end parameter # 'programming is' string is checked result = text.endswith(('is', 'an'), 0, 14) # prints True print(result)
Produzione
Falso vero vero
Se è necessario controllare se una stringa inizia con il prefisso specificato, è possibile utilizzare il metodo startswith () in Python.