startswith( prefix[, start[, end]]) Query

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Sep 6 10:23:59 EDT 2007


cjt22 at bath.ac.uk a écrit :
> Hi
> 
> startswith( prefix[, start[, end]])  States:
> 
> Return True if string starts with the prefix, otherwise return False.
> prefix can also be a tuple of suffixes to look for. However when I try
> and add a tuple of suffixes I get the following error:
> 
> Type Error: expected a character buffer object
> 
> For example:
> 
> file = f.readlines()
> for line in file:

slightly OT, but:
1/ you should not use 'file' as an identifier, it shadowas the builtin 
file type
2/ FWIW, it's also a pretty bad naming choice for a list of lines - why 
not just name this list 'lines' ?-)
3/ anyway, unless you need to store this whole list in memory, you'd be 
better using the iterator idiom (Python files are iterables):

f = open('some_file.ext')
for line in f:
   print line


>     if line.startswith(("abc","df"))
>         CODE
> 
> It would generate the above error

May I suggest that you read the appropriate version of the doc ? That 
is, the one corresponding to your installed Python version ?-)

Passing a tuple to str.startswith is new in 2.5. I bet you're trying it 
on a 2.4 or older version.

> To overcome this problem, I am currently just joining individual
> startswith methods
> i.e. if line.startswith("if") or line.startswith("df")
> but know there must be a way to define all my suffixes in one tuple.

You may want to try with a regexp, but I'm not sure it's worth it (hint: 
the timeit module is great for quick small benchmarks).

Else, you could as well write your own testing function:

def str_starts_with(astring, *prefixes):
   startswith = astring.startswith
   for prefix in prefixes:
     if startswith(prefix):
       return true
   return false

for line in f:
   if str_starts_with(line, 'abc, 'de', 'xxx'):
     # CODE HERE

HTH



More information about the Python-list mailing list