Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search for a string in a list element 1

Status
Not open for further replies.

vodkadrinker

Technical User
May 16, 2002
163
0
0
GB
I am trying to find a string in a list element.

example data
Code:
'/home/myfiles/abc.bob/a file'
'/home/myfiles/abc.bob/b file'
'/home/myfiles/bbb.bob/a file'

So from the data I want to find any line with "abc.bob" and then just count the number of them.

The data is read into a list called "info"

This is the example code that I am trying
Python:
for line in info:
    if 'abc.bob' in line:
        abc_count += 1

But this does not find the string in the line, please can someone point me in the right direction.
To add to this when I use the same code and read in the data from a file it works fine, but I am working with
someone else's code and they read it into list.
 
For me,
Code:
lsta=['/home/myfiles/abc.bob/a file','/home/myfiles/abc.bob/b file','/home/myfiles/bbb.bob/a file']
abccount=0
for a in lsta:
    if 'abc.bob' in a: abccount+=1
print abccount
yields 2, as it should.

You can also achieve the same result with list comprehension:
Code:
lsta=['/home/myfiles/abc.bob/a file','/home/myfiles/abc.bob/b file','/home/myfiles/bbb.bob/a file']
print len([a for a in lsta if 'abc.bob' in a])

_________________
Bob Rashkin
 
Thanks Bob now I know this should work, I will check back through.

Funny enough if I add a total line count it gives me the correct number of lines.

Python:
for line in info:
    total_count += 1
    if 'abc.bob' in line:
        abc_count += 1
 
Found the answer to the problem, when there is a space in the file/directory name it splits the elements.

So the list is being seen as
Python:
['/home/myfiles/abc.bob/a','file']


Instead of
Python:
['/home/myfiles/abc.bob/a file']

Thanks for your help Bob, as it helped me to look deeper into the problem and confirmed my code (I still am a python newbie).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top