Skip to content
Advertisement

Python, print from keyword to next dot

So this is my code

JavaScript

At the moment it opens the file which you are setting in the first input and searches this file line by line for the keyword you set on the second input.

As it is now it prints the whole line where the keyword was found.

What I wanna do is just to print from the keyword onwards to the next dot.

For example: file.txt

JavaScript

keyword = my

The actual result prints both lines because both lines contain “my”. But it only should print this:

JavaScript

Didn’t find any answer so far, please help me

Advertisement

Answer

We can splice into the string line by using the operator []. With the help of str.find(), we can determine the little portion we need to print. From the documentation:

JavaScript

So here’s how we could rewrite the code:

JavaScript

Keep in mind that this will get wonky if there is a period ‘.’ inside the string_to_search. To make sure you print out the whole string in this case, do this instead:

JavaScript

This skips the whole length of string_to_search before looking for periods.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement