Python niz se konča z ()

Metoda ENDWITH () vrne True, če se niz konča z navedeno pripono. Če ne, se vrne False.

Sintaksa endswith()je:

 str.endswith (pripona (, začetek (, konec)))

konča s parametri ()

endswith()Traja tri parametre:

  • pripona - niz ali sklop priponk, ki jih je treba preveriti
  • start (neobvezno) - začetni položaj, kjer je treba v priponi preveriti pripono .
  • konec (neobvezno) - končni položaj, kjer je treba v nizu preveriti pripono .

Vrnjena vrednost od ENDSWith ()

endswith()Metoda vrne logično vrednost.

  • Vrne True, če se nizi končajo z navedeno pripono.
  • Vrne False, če se niz ne konča z navedeno pripono.

Primer 1: endswith () Brez začetnega in končnega parametra

 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)

Izhod

 False True True

Primer 2: endswith () Z začetkom in koncem Parametri

 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)

Izhod

 True False True

Mimo podajanja Tuple do konca z ()

endswith()Metodi v Pythonu je mogoče predati pripone tuple .

Če se niz konča s katerim koli elementom nabora, endswith()vrne True. Če ne, se vrne False

Primer 3: konča se z () s pripono Tuple

 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)

Izhod

 False True True

Če morate preveriti, ali se niz začne z določeno predpono, lahko v Pythonu uporabite metodo startwith ().

Zanimive Članki...