Python String se začne z ()

Metoda startwith () vrne True, če se niz začne z določeno predpono (string). Če ne, se vrne False.

Sintaksa startswith()je:

 str.startswith (predpona (, začetek (, konec)))

startwith () Parametri

startswith() metoda zajema največ tri parametre:

  • predpona - niz ali niz nizov, ki jih je treba preveriti
  • start (neobvezno) - Začetni položaj, kjer je treba v nizu preveriti predpono .
  • konec (neobvezno) - končni položaj, kjer je treba v nizu preveriti predpono .

Vrnjena vrednost od startwith ()

startswith() vrne logično vrednost.

  • Vrne True, če se niz začne s podano predpono.
  • Vrne False, če se niz ne začne s podano predpono.

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

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

Izhod

 False True True

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

 text = "Python programming is easy." # start parameter: 7 # 'programming is easy.' string is searched result = text.startswith('programming is', 7) print(result) # start: 7, end: 18 # 'programming' string is searched result = text.startswith('programming is', 7, 18) print(result) result = text.startswith('program', 7, 18) print(result)

Izhod

 True False True

Prenos Tuplea na startwith ()

startswith()Metodi v Pythonu je mogoče predati vrsto predpon .

Če se niz začne s katerim koli elementom nabora, startswith()vrne True. Če ne, se vrne False

Primer 3: startwith () s predpono Tuple

 text = "programming is easy" result = text.startswith(('python', 'programming')) # prints True print(result) result = text.startswith(('is', 'easy', 'java')) # prints False print(result) # With start and end parameter # 'is easy' string is checked result = text.startswith(('programming', 'easy'), 12, 19) # prints False print(result)

Izhod

 True False False

Če morate preveriti, ali se niz konča z določeno pripono, lahko v Pythonu uporabite metodo ENDWITH ().

Zanimive Članki...