How to manipulate strings with ".find"

1

Can I use ".find" to make the program search for a word within a typed text and say whether it exists or not (true or false) and in which line of text it is located, if not, which command use to do this? What I already have:

a = str(input())
#output: Criando um exemplo.
print(a.find('exemplo'))
    
asked by anonymous 25.10.2017 / 19:39

1 answer

4

The find method should be used only if you are interested in the position of the occurrence in string , that is, in which part of the string the desired value was found . If the intention is only to verify if it is found, the ideal is to use the in :

texto = input()
if "exemplo" in texto:
    print("Encontrou")

See working at Ideone | Repl.it

Remembering that in Python 3, the return of the input function is already a string , so there is no need to convert it again.

If it's really interesting to know what position the desired value was in, you can do something like:

texto = input()
index = texto.find("exemplo")
if index >= 0:
    print("Encontrou na posição %d" % index)

See working at Ideone | Repl.it

    
25.10.2017 / 19:51