Python virknes endswith ()

Metode endswith () atgriež vērtību True, ja virkne beidzas ar norādīto sufiksu. Ja nē, tas atgriež False.

Sintakse endswith()ir:

 str.endswith (sufikss (, start (, end)))

endswith () parametri

Tam endswith()nepieciešami trīs parametri:

  • sufikss - pārbaudāmo sufiksu virkne vai virkne
  • sākums (pēc izvēles) - sākuma pozīcija, kur virknē jāpārbauda sufikss .
  • beigas (pēc izvēles) - beigu pozīcija, kur virknē jāpārbauda sufikss .

Atgriešanās vērtība no endswith ()

endswith()Metode atgriež boolean.

  • Tas atgriež vērtību True, ja virknes beidzas ar norādīto sufiksu.
  • Tas atgriež False, ja virkne nebeidzas ar norādīto sufiksu.

1. piemērs: endswith () bez sākuma un beigu parametriem

 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)

Rezultāts

 False True True

2. piemērs: endswith () ar sākuma un beigu parametriem

 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)

Rezultāts

 True Nepatiesa True

Pabraucot Tuple ar endswith ()

endswith()Python metodei ir iespējams nodot dubultu sufiksus .

Ja virkne beidzas ar kādu kopas elementu, endswith()atgriež vērtību True. Ja nē, tas atgriež False

3. piemērs: endswith () Ar Tuple Suffix

 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)

Rezultāts

 False True True

Ja jums jāpārbauda, ​​vai virkne sākas ar norādīto prefiksu, Python varat izmantot metodi startswith ().

Interesanti raksti...