English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Se a string começar com o prefixo especificado (string), o método startswith() retornará True. Se não, retornará False.
A sintaxe do startswith() é:
str.startswith(prefix[, start[, end]])
O método startswith() pode usar até três parâmetros:
prefix -String ou tupla de strings a ser verificada
start(Opcional)- Para verificar na stringPrefixoPosição inicial.
end (Opcional)- Para verificar na stringPrefixoPosição final.
O método startswith() retorna um valor booleano.
Se a string começar com o prefixo especificado, retorna True.
Se a string não começar com o prefixo especificado, retorna False.
text = "Python é fácil de aprender." result = text.startswith('é fácil') # Retornar False print(result) result = text.startswith('Python é') # Retorno True print(result) result = text.startswith('Python é fácil de aprender.') # Retorno True print(result)
Quando o programa é executado, a saída é:
False True True
text = "Python programming is easy." # Parâmetro de início: 7 # 'programming is easy.' string está sendo pesquisada result = text.startswith('programming is', 7) print(result) # start: 7, end: 18 # 'programming' string está sendo pesquisada result = text.startswith('programming is', 7, 18) print(result) result = text.startswith('program', 7, 18) print(result)
Quando o programa é executado, a saída é:
True False True
Em Python, pode-se passar uma tupla de prefixo para o método startswith()
Se a string começar com qualquer item da tupla, o startswith() retorna True. Caso contrário, retorna False
text = "programming is easy" result = text.startswith(('python', 'programming')) # Saída True print(result) result = text.startswith(('is', 'easy', 'java')) # Saída False print(result) # Com parâmetros start e end # 'is easy' string está sendo verificada result = text.startswith(('programming', 'easy'), 12, 19) # Saída False print(result)
Quando o programa é executado, a saída é:
True False False
Se precisar verificar se uma string termina com um sufixo específico, podeem PythonUsoMétodo endswith().