How to print lines that have a certain word in python?

Asked

Viewed 76 times

0

I’m taking a test and she has this question : "Make a program that receives sentences and insert them into a new file called string.txt. Next the program should read the file and print only the lines that have the word Python. In addition, the program must inform the number of existing lines in the file."

I’ve already been able to insert the lines into the file and count them. But I can’t print the lines that have the word Python...

ql = 0
frase1 = str(input('Digite a primeira frase: '))
frase2 = str(input('Digite a segunda frase: '))
frase3 = str(input('Digite a terceira frase: '))

arquivo3 = open("string.txt","w")

arquivo3.write(f'{frase1}')
arquivo3.write(f'\n{frase2}')
arquivo3.write(f'\n{frase3}')

arquivo3 = open("string.txt","r")
for linha in arquivo3:
    ql += 1
    if linha in 'Python' or 'python' :
        print(linha)

    else:
        pass
print(f'Existem {ql} linhas')

1 answer

0


Just invert the test parameters.

Original: if line in 'Python' or 'python' : print(line)

Proposal: if 'Python' in line or 'python' in line: print(line)

  • Boy, just lack of attention really ahahah, thank you!

Browser other questions tagged

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