473,698 Members | 2,524 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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:
if line.startswith (("abc","df") )
CODE

It would generate the above error

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.

Thanks in advance

Sep 6 '07 #1
11 5176
cj***@bath.ac.u k wrote:
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.
That particular aspect of the functionality (the multiple
prefixes in a tuple) was only added Python 2.5. If you're
using <= 2.4 you'll need to use "or" or some other approach,
eg looping over a sequence of prefixes.

TJG
Sep 6 '07 #2
On Sep 6, 7:09 am, cj...@bath.ac.u k wrote:
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:
if line.startswith (("abc","df") )
CODE

It would generate the above error
(snipped)

You see to be using an older version of Python.
For me it works as advertised with 2.5.1,
but runs into the problem you described with 2.4.4:

Python 2.5.1c1 (r251c1:54692, Apr 17 2007, 21:12:16)
[GCC 4.0.0 (Apple Computer, Inc. build 5026)] on darwin
Type "help", "copyright" , "credits" or "license" for more information.
>>line = "foobar"
if line.startswith (("foo", "bar")): print line
....
foobar
>>if line.startswith (("foo", "bar")):
.... print line
....
foobar
VS.

Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright" , "credits" or "license" for more information.
>>line = "foobar"
if line.startswith (("foo", "bar")): print line
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: expected a character buffer object
--
Hope this helps,
Steven

Sep 6 '07 #3
cj***@bath.ac.u k 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.startsw ith
for prefix in prefixes:
if startswith(pref ix):
return true
return false

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

HTH
Sep 6 '07 #4
On 06/09/07, Bruno Desthuilliers
<br************ ********@wtf.we bsiteburo.oops. comwrote:
>
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.startsw ith
for prefix in prefixes:
if startswith(pref ix):
return true
return false

for line in f:
if str_starts_with (line, 'abc, 'de', 'xxx'):
# CODE HERE
Isn't slicing still faster than startswith? As you mention timeit,
then you should probably add slicing to the pot too :)

if astring[:len(prefix)] == prefix:
do_stuff()

:)
Sep 6 '07 #5
Else, you could as well write your own testing function:

def str_starts_with (astring, *prefixes):
startswith = astring.startsw ith
for prefix in prefixes:
if startswith(pref ix):
return true
return false
What is the reason for
startswith = astring.startsw ith
startswith(pref ix)

instead of
astring.startsw ith(prefix)

Sep 7 '07 #6
TheFlyingDutchm an wrote:
>Else, you could as well write your own testing function:

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

What is the reason for
startswith = astring.startsw ith
startswith(pref ix)

instead of
astring.startsw ith(prefix)
It's an optimization: the assigment creates a "bound method" (i.e. a
method associated with a specific string instance) and avoids having to
look up the startswith method of astring for each iteration of the inner
loop.

Probably not really necessary, though, and they do say that premature
optimization is the root of all evil ...

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Sep 7 '07 #7
Steve Holden a écrit :
TheFlyingDutchm an wrote:
>>Else, you could as well write your own testing function:

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

What is the reason for
startswith = astring.startsw ith
startswith(pref ix)

instead of
astring.startsw ith(prefix)
It's an optimization: the assigment creates a "bound method" (i.e. a
method associated with a specific string instance) and avoids having to
look up the startswith method of astring for each iteration of the inner
loop.

Probably not really necessary, though, and they do say that premature
optimization is the root of all evil ...
I wouldn't call this one "premature" optimization, since it doesn't
change the algorithm, doesn't introduce (much) complication, and is
proven to really save on lookup time.

Now I do agree that unless you have quite a lot of prefixes to test, it
might not be that necessary in this particular case...
Sep 7 '07 #8
"Tim Williams" <li********@tdw .netwrote:
Isn't slicing still faster than startswith? As you mention timeit,
then you should probably add slicing to the pot too :)
Possibly, but there are so many other factors that affect the timing
that writing it clearly should be your first choice.

Some timings:

@echo off
setlocal
cd \python25\lib
echo "startswith "
...\python timeit.py -s "s='abracadabra 1'*1000;t='abra cadabra2'" s.startswith(t)
...\python timeit.py -s "s='abracadabra 1'*1000;t='abra cadabra1'" s.startswith(t)
echo "prebound startswith"
...\python timeit.py -s "s='abracadabra 1'*1000;t='abra cadabra2';start swith=s.startsw ith" startswith(t)
...\python timeit.py -s "s='abracadabra 1'*1000;t='abra cadabra1';start swith=s.startsw ith" startswith(t)
echo "slice with len"
...\python timeit.py -s "s='abracadabra 1'*1000;t='abra cadabra2'" s[:len(t)]==t
...\python timeit.py -s "s='abracadabra 1'*1000;t='abra cadabra1'" s[:len(t)]==t
echo "slice with magic number"
...\python timeit.py -s "s='abracadabra 1'*1000;t='abra cadabra2'" s[:12]==t
...\python timeit.py -s "s='abracadabra 1'*1000;t='abra cadabra1'" s[:12]==t

and typical output from this is:

"startswith "
1000000 loops, best of 3: 0.542 usec per loop
1000000 loops, best of 3: 0.514 usec per loop
"prebound startswith"
1000000 loops, best of 3: 0.472 usec per loop
1000000 loops, best of 3: 0.474 usec per loop
"slice with len"
1000000 loops, best of 3: 0.501 usec per loop
1000000 loops, best of 3: 0.456 usec per loop
"slice with magic number"
1000000 loops, best of 3: 0.34 usec per loop
1000000 loops, best of 3: 0.315 usec per loop

So for these particular strings, the naive slice wins if the comparison is
true, but loses to the pre-bound method if the comparison fails. The slice is
taking a hit from calling len every time, so pre-calculating the length
(which should be possible in the same situations as pre-binding startswith)
might be worthwhile, but I would still favour using startswith unless I knew
the code was time critical.
Sep 7 '07 #9
Bruno Desthuilliers wrote:
Steve Holden a écrit :
[...]
>>
Probably not really necessary, though, and they do say that premature
optimization is the root of all evil ...

I wouldn't call this one "premature" optimization, since it doesn't
change the algorithm, doesn't introduce (much) complication, and is
proven to really save on lookup time.

Now I do agree that unless you have quite a lot of prefixes to test, it
might not be that necessary in this particular case...
The defense rests.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Sep 7 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
6052
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text containing norwegian special characters æ, ø and å. >>> liste =
8
3065
by: Christian Gudrian | last post by:
Hello, there! Given a list with strings. What is the most pythonic way to check if a given string starts with one of the strings in that list? I started by composing a regular expression pattern which consists of all the strings in the list separated by "|" in a for loop. Then I used that pattern to do a regexp match.
18
3042
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases...
11
2427
by: Dan Sugalski | last post by:
Is there any good way to speed up SQL that uses like and has placeholders? Here's the scoop. I've got a system that uses a lot of pre-generated SQL with placeholders in it. At runtime these SQL statements are fired off (through the C PQexecParams function, if that matters) for execution. No prepares or anything, just bare statements with $1 and friends, with the values passed in as parameters. Straightforward, and no big deal. ...
5
4707
by: metaperl | last post by:
I just finished answering a question in #python because someone tried to match using ... well.. match() but did not realize that match() is actually startswith() for regexps. I suggest: re.compile('blah').atstartof(string) re.compile('blah').atendof(string) But it will never happen.
8
1623
by: js | last post by:
Hello, list. I have a list of sentence in text files that I use to filter-out some data. I managed the list so badly that now it's become literally a mess. Let's say the list has a sentence below 1. "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. "
4
3289
by: =?utf-8?B?Qm9yaXMgRHXFoWVr?= | last post by:
Hello, what is the use-case of parameter "start" in string's "endswith" method? Consider the following minimal example: a = "testing" suffix="ing" a.endswith(suffix, 2) Significance of "end" is obvious. But not so for "start".
6
2109
Colloid Snake
by: Colloid Snake | last post by:
Hello, I'm running into an odd problem - well, at least I think it's odd, but that's probably because I have a Cygwin screen burned into my retinas from staring at it for so long. When I run my script below, the output lines print twice. I'm hoping it's something simple (and yet kind of not, because then I look like a fool... oh well), but hopefully a fresh pair of eyes might be able to help me. Oh, and please feel free to comment on how...
4
7723
by: Deckarep | last post by:
Hey everyone, Is there a more elegant or cleaner way of accomplishing the following null check? List<stringmyString = null; //Purposely null list of strings to show the example XElement element = new XElement("Strings",
0
8678
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9166
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8899
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5861
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.