How to manipulate strings with ". find"

Asked

Viewed 4,647 times

1

I can 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 what line of text is located, if not, what command do I use to do this? What I’ve got so far:

a = str(input())
#output: Criando um exemplo.
print(a.find('exemplo'))

1 answer

4

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

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

See working on Ideone | Repl.it

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

If it is really interesting to know in which position the desired value occurred, it is possible to do something like:

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

See working on Ideone | Repl.it

  • Is there any way to signal in which line the word is, in the case of large texts?

  • 1

    @Lucassouza yes. If this text is in a variable, the simplest would be to perform a split on the line breaks, \n, run them and check line by line if you have the desired content.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.