Reputation: 1
char1= "P"
length=5
f = open("wl.txt", 'r')
for line in f:
if len(line)==length and line.rstrip() == char1:
z=Counter(line)
print z
I want to output only lines where length=5 and contains character p.So far
f = open("wl.txt", 'r')
for line in f:
if len(line)==length :#This one only works with the length
z=Counter(line)
print z
Any guess someone?
Upvotes: 0
Views: 130
Reputation: 142216
Your problem is:
if len(line)==length and line.rstrip() == char1:
If a line is 5 characters long, then after removing trailing whitespace, you're then comparing to see if it's equal to a string of length 1... 'abcde' is never going to equal 'p' for instance, and your check will never run if your line contains 'p' as it's not 5 characters...
I'm not sure what you're trying to do with Counter
Corrected code is:
# note in capitals to indicate 'constants'
LENGTH = 5
CHAR = 'p'
with open('wl.txt') as fin:
for line in fin:
# Check length *after* any trailing whitespace has been removed
# and that CHAR appears anywhere **in** the line
if len(line.rstrip()) == LENGTH and CHAR in line:
print 'match:', line
Upvotes: 5