January 8th, 2005, 12:01 AM
Find string in files
Ok so i dont want to append the same text to my file because that would look stupid! Anyway i need some tips on how to search book.txt for the string "Address added" so i dont reappend! So if its already the then goto end of code or? im a n00b
January 8th, 2005, 02:40 PM
Python has a very elegant way of looking for substrings; using the 'in' keyword. Heres an example:
Note: This is a case sensitive, if you want to do a case insensitive search then you need to convert the search-string and source-string to the same case; usually to lowercase using the lower() string-method .
>>> aString = 'This string can be searched for a substring using the in operator'
>>> 'This' in aString
>>> 'searched' in aString
>>> 'for a substring' in aString
>>> 'For a substring' in aString
>>> 'FOR A SUBSTRING' in aString
>>> 'operator' in aString
>>> if 'using the in operator' in aString:
... print 'Found the substring!'
Found the substring!
So If you wanted to search a file you would usually read() the file into a variable and then do the search just like I did above: if the substring is found then True is returned, else False.
Hope this helps ,
January 8th, 2005, 07:49 PM
January 8th, 2005, 07:50 PM
Put everything into a while loop started and ended by a boolean.
done = False
while done = False
to finish the code do this:
done = True
January 9th, 2005, 11:50 AM
January 9th, 2005, 12:02 PM
You could import the sys module and call sys.exit() although by far my favorite way to exit a program is by raising 'SystemExit'.
This is amazingly simple, and if you know how to use/handle exceptions in Python then it can be surprisingly powerful .
Python 2.4 (#1, Dec 10 2004, 19:59:18)
[GCC 3.3.3 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> userName = 'Mark'
>>> if userName == 'Mark':
... raise SystemExit
January 9th, 2005, 12:19 PM
Nice one =) I haven't gotten that far in the tuturial yet heh. I'm working on sets.
January 9th, 2005, 12:50 PM
Ooh, nice. I've never seen that before.