Python String startswith ()

O método startswith () retorna True se uma string começa com o prefixo especificado (string). Caso contrário, retorna False.

A sintaxe de startswith()é:

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

Startwith () Parâmetros

startswith() método leva no máximo três parâmetros:

  • prefix - String ou tupla de strings a serem verificadas
  • start (opcional) - Posição inicial onde o prefixo deve ser verificado dentro da string.
  • end (opcional) - Posição final onde o prefixo deve ser verificado dentro da string.

Valor de retorno de startswith ()

startswith() método retorna um booleano.

  • Retorna True se a string começa com o prefixo especificado.
  • Retorna False se a string não começar com o prefixo especificado.

Exemplo 1: startswith () Sem parâmetros de início e fim

 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)

Resultado

 Falso Verdadeiro

Exemplo 2: startswith () Com parâmetros de início e fim

 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)

Resultado

 Verdadeiro Falso Verdadeiro

Passando tupla para começa com ()

É possível passar uma tupla de prefixos para o startswith()método em Python.

Se a string começar com qualquer item da tupla, startswith()retorna True. Caso contrário, retorna False

Exemplo 3: startswith () Com prefixo de tupla

 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)

Resultado

 Verdadeiro Falso Falso

Se você precisa verificar se uma string termina com o sufixo especificado, você pode usar o método endswith () em Python.

Artigos interessantes...