November 16th, 2013, 07:49 AM
Help with python
I need to create a code which extracts a file which looks like this:
This is line 2
This is line 3
I need to create a function which demands the file, and a word.
It check's if the word is the starting words of each line, and returns the number of lines in which it is the first word.
if i extract the file above , and look for the word "This" , i should be return the value : 2.
I didn't know how to check if the word is the first word in the line, so someone told me to use "startwith".
the problem is , i receive nemours errors such as, you can't use the "startwith" on a str, or a list.
def count_lines_with_prefix(path, prefix):
for line in path.readlines():
So i don't know what should i do.
could you tell me how should i alter my code?
thank you for your time.
November 16th, 2013, 09:11 AM
The correct string method is startswith() (note the second "s").
>>> "abc def".startswith("ab")
Also, your split() statement, d=line.split(), is completely superfluous. Just use startswith on "line".
November 16th, 2013, 11:19 AM
Lines count=0 and return count should be outside the for loop.
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25