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

Tutorial di base Python

Controllo dei flussi Python

Funzione di Python

Tipi di dati di Python

Operazioni di file Python

Oggetti e classi Python

Date e ora Python

Conoscenze avanzate Python

Manuale di Python

Utilizzo e esempio di startswith() per stringhe Python

Metodi di stringa di Python

Se la stringa inizia con il prefisso specificato (stringa), il metodo startswith() restituirà True. Se non lo fa, restituirà False.

Sintassi di startswith()

str.startswith(prefix[, start[, end]])

Parametri di startswith()

Il metodo startswith() può utilizzare al massimo tre parametri:

  • prefix - Stringa o tuple di stringhe da controllare

  • start(opzionale)-  Da controllare nella stringaPrefissoPosizione di inizio.

  • end (opzionale)-  Da controllare nella stringaPrefissoPosizione di fine.

Valore di ritorno di startswith()

Il metodo startswith() restituisce un valore booleano.

  • Se la stringa inizia con il prefisso specificato, viene restituito True.

  • Se la stringa non inizia con il prefisso specificato, viene restituito False.

Esempio 1: startswith() senza parametri start e end

text = "Python is easy to learn."
result = text.startswith('is easy')
# Restituisce False
print(result)
result = text.startswith('Python is')
# Restituisce True
print(result)
result = text.startswith('Python is easy to learn.')
# Restituisce True
print(result)

Quando si esegue il programma, l'output è:

False
True
True

Esempio 2: startswith() con parametri start e end

text = "Python programming is easy."
# Parametro di inizio: 7
# La stringa 'programming is easy.' viene cercata
result = text.startswith('programming is', 7)
print(result)
# start: 7, end: 18
# La stringa 'programming' viene cercata
result = text.startswith('programming is', 7, 18)
print(result)
result = text.startswith('program', 7, 18)
print(result)

Quando si esegue il programma, l'output è:

True
False
True

Passare una tupla a startswith()

In Python, si può passare una tupla di prefissi al metodo startswith()

Se una stringa inizia con uno qualsiasi degli elementi di una tupla, startswith() restituisce True. Altrimenti, restituisce False

Esempio 3: startswith() con prefisso di tuple

text = "programming is easy"
result = text.startswith(('python', 'programming'))
# Output True
print(result)
result = text.startswith(('is', 'easy', 'java'))
# Output False
print(result)
# Con parametri start e end
# La stringa 'is easy' viene verificata
result = text.startswith(('programming', 'easy'), 12, 19)
# Output False
print(result)

Quando si esegue il programma, l'output è:

True
False
False

Se si desidera verificare se una stringa termina con uno specifico suffisso, allora si puòIn PythonUsareMetodo endswith().

Metodi di stringa di Python