Searching Strings for Specific EndingsBeginnings


Searching Strings for Specific Endings/Beginnings

if f.endswith('.py'):     print "Python file: " + f elif f.endswith('.txt'):     print "Text file: " + f

The endswith(suffix, [, start, [,end]]) and startswith(prefix, [, start, [,end]]) methods provide a simple and safe way to determine whether a string begins or ends with a specific prefix or suffix, respectively. The first argument is a string used to compare to the prefix or suffix of the string. The endswith and startswith methods are dynamic enough for you to limit the search to within a specific range of the string using the start and/or end arguments.

Note

The endswith and startswith methods are extremely useful when parsing file lists for extensions or filenames.


import os for f in os.listdir('C:\\txtfiles'):     if f.endswith('.py'):         print "Python file: " + f     elif f.endswith('.txt'):         print "Text file: " + f


end_str.py

Python file: comp_str.py Python file: end_str.py Python file: eval_str.py Python file: join_str.py Text file: output.txt Python file: replace_str.py Python file: search_str.py Python file: split_str.py Python file: trim_str.py Python file: unicode_str.py Python file: var_str.py


Output from end_str.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net