[python] Find specific characters in a string

Asked 2 years ago, Updated 2 years ago, 33 views

file=open("python_07_05.txt", 'w')

words="aa"
while(words!="Q"):
    words=input()
#words.split()    
word=input()

if words.find(word):
    infile.write("find word : "+word)

infile.close()

outfile=open("python_07_05.txt",'r')
text=outfile.read()
print(text)
outfile.close()

Is there a way to prevent searching when I enter data such as "I heart that you're set down" in the following code and type "you" in the word? I want to recognize you're as one word so that I can't search if I search for you.

python python3

2022-09-22 15:39

1 Answers

First of all, the code below is wrong.

if words.find(word):

The find function finds the string and returns the position, but returns -1 if not found.

False : 0

True: All non-zero numbers

As shown above, -1 is True.

In other words, even if it is not found, the inside of the if block is executed.

If you want the inside of the if block to run only when you find it as intended, you need to code it as below.

if words.find(word) >= 0:

If you want to find you and you're separately, Regular Expression can solve it, but a simpler method can be implemented by adding a space before and after the string you want to find.

When you do find, put a space in front of the word and try it.

If you do the following, you're cannot be found.

if words.find(" you ") >= 0:
    print("find word")

Add)

Please refer to the code below

words = "I heard that you're settled down"
word = "you"

if words.find(" " + word + " ") >= 0:
    print("find word")

If you think about the rest a little bit, you will be able to do it on your own.


2022-09-22 15:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.