[Tutor] how to print lines which contain matching words or strings

Avi Gross avigross at verizon.net
Sun Nov 18 20:13:41 EST 2018


Asad,

As others have already pointed out, your request is far from clear. 

Ignoring the strange use of words, and trying to get the gist of the
request, would this be close to what you wanted to say?

You have a file you want to open and process a line at a time. You want to
select just lines that meet your criteria and print them while ignoring the
rest.

So what are the criteria? It sounds like you have a list of criteria that
might be called patterns. Your example shows a heterogenous collection:

[A ,"B is good" ,123456 , "C "]

A is either an error or the name of a variable that contains something. We
might want a hint as searching for any old object makes no sense.

The second and fourth are exact strings. No special regular expression
pattern. Searching for them is trivial using normal string functionality.
Assuming they can be anywhere in a line:

>>> line1 = "Vitamin B is good for you and so is vitamin C"
>>> line2 = "Currently nonsensical."
>>> line3 = ""
>>> "B is good" in line1
True
>>> "B is good" in line2
False
>>> "B is good" in line3
False
>>> "C" in line1
True
>>> "C" in line2
True
>>> "C" in line2
True

To test everything in a list, you need code like for each line:

for whatever in [A ,"B is good" ,123456 , "C "]
    If whatever in line: print(line)

Actually, the above could print multiple copies so you should break out
after any one matches.

123456 is a challenge to match. You could search for str(whatever) perhaps.

Enough. First explain what you really want.

If you want to do a more general search using regular expressions, then the
list of things to search for would be all the string in RE format. You could
search multiple times or use the OR operator carefully inside one regular
expression. You have not stated any need to tell what was matched or where
it is the line so that would be yet another story.

-----Original Message-----
From: Tutor <tutor-bounces+avigross=verizon.net at python.org> On Behalf Of
Asad
Sent: Sunday, November 18, 2018 10:19 AM
To: tutor at python.org
Subject: [Tutor] how to print lines which contain matching words or strings

Hi All ,

       I have a set of words and strings :

like :

p = [A ,"B is good" ,123456 , "C "]

I have a file in which I need to print only the lines which matches the
pattern in p

thanks,

--
Asad Hasan
+91 9582111698
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list