English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial di base Python

Controllo dei flussi Python

Funzione in Python

Tipi di dati in Python

Operazioni di file Python

Oggetti e classi Python

Data e ora Python

Conoscenze avanzate di Python

Manuale di Python

Utilizzo e esempio di endsWith() per stringhe Python

Metodi di stringa di Python

Se la stringa termina con il valore specificato, il metodo endsWith() restituisce True. Se non lo fa, restituisce False.

La sintassi di endsWith() è:

str.endswith(suffix[, start[, end]])

Parametri di endsWith()

endsWith() ha tre parametri:

  • suffix - La stringa di suffisso da controllare o il tuple

  • start(opzionale)- Controlla nella stringasuffixPosizione di inizio.

  • end(opzionale)- Controlla nella stringasuffixPosizione di fine.

Valore di ritorno di endsWith()

Il metodo endsWith() restituisce un valore booleano.

  • La stringa termina con il valore specificato, restituisce True.

  • Se la stringa non termina con il valore specificato, restituisce False.

Esempio 1: endsWith() senza parametri di inizio e fine

text = "Python è facile da imparare."
result = text.endswith('da imparare')
# Restituisce False
print(result)
result = text.endswith('da imparare.')
# Restituisce True
print(result)
result = text.endswith('Python è facile da imparare.')
# Restituisce True
print(result)

Quando si esegue il programma, l'output è:

False
True
True

Esempio 2: endsWith() con parametri di inizio e fine

text = "Python programmazione è facile da imparare."
# Parametro start: 7
# La stringa "programming is easy to learn." è la stringa da cercare
result = text.endswith('learn.', 7)
print(result)
# Inserire contemporaneamente i parametri start e end
# start: 7, end: 26
# La stringa "programming is easy" è la stringa da cercare
result = text.endswith('is', 7, 26)
# Restituisce False
print(result)
result = text.endswith('easy', 7, 26)
# Restituisce True
print(result)

Quando si esegue il programma, l'output è:

True
False
True

Passare una tupla a endswith()

In Python, è possibile passare una tupla come valore specifico al metodo endswith()

Se una stringa termina con qualsiasi elemento di una tupla, endswith() restituisce True. Altrimenti, restituisce False

Esempio 3: endswith() con tuple

text = "programming is easy"
result = text.endswith(('programming', 'python'))
# Output False
print(result)
result = text.endswith(('python', 'easy', 'java'))
# Output True
print(result)
# Con i parametri start e end
# La stringa 'programming is' viene verificata
result = text.endswith(('is', 'an'), 0, 14)
# Output True
print(result)

Quando si esegue il programma, l'output è:

False
True
True

Se si desidera verificare se una stringa inizia con un prefisso specifico, è possibile farlo in PythonMetodo startswith().

Metodi di stringa di Python