473,471 Members | 1,858 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

new string function suggestion

What do people think of this?

'prefixed string'.lchop('prefix') == 'ed string'
'string with suffix'.rchop('suffix') == 'string with '
'prefix and suffix.chop('prefix', 'suffix') == ' and '

The names are analogous to strip, rstrip, and lstrip. But the functionality
is basically this:

def lchop(self, prefix):
assert self.startswith(prefix)
return self[len(prefix):]

def rchop(self, suffix):
assert self.endswith(suffix)
return self[:-len(suffix]

def chop(self, prefix, suffix):
assert self.startswith(prefix)
assert self.endswith(suffix)
return self[len(prefix):-len(suffix]

The assert can be a raise of an appropriate exception instead. I find this
to be a very common need, and often newbies assume that the
strip/lstrip/rstrip family behaves like this, but of course they don't.

I get tired of writing stuff like:

if path.startswith('html/'):
path = path[len('html/'):]
elif s.startswith('text/'):
path = path[len('text/'):]

It just gets tedious, and there is duplication. Instead I could just write:

try:
path = path.lchop('html/')
path = path.lchop('text/')
except SomeException:
pass

Does anyone else find this to be a common need? Has this been suggested
before?

Andy
Jul 19 '05 #1
4 2200
Andy wrote:
What do people think of this?

'prefixed string'.lchop('prefix') == 'ed string'
'string with suffix'.rchop('suffix') == 'string with '
'prefix and suffix.chop('prefix', 'suffix') == ' and '
Your use case is
I get tired of writing stuff like:

if path.startswith('html/'):
path = path[len('html/'):]
elif s.startswith('text/'):
path = path[len('text/'):]

It just gets tedious, and there is duplication. Instead I could just write:

try:
path = path.lchop('html/')
path = path.lchop('text/')
except SomeException:
pass
But your posted code doesn't implement your use case. Consider
if path == "html/text/something". Then the if/elif code sets
path to "text/something" while the lchop code sets it to "something".

One thing to consider is a function (or string method) which
is designed around the 'or' function, like this. (Named 'lchop2'
but it doesn't give the same interface as your code.)

def lchop2(s, prefix):
if s.startswith(prefix):
return s[len(prefix):]
return None

path = lchop2(path, "html/") or lchop2(path, "text/") or path
If I saw a function named "lchop" (or perhaps named "lchomp") I
would expect it to be (named 'lchomp3' so I can distinguish
between it and the other two)

def lchop3(s, prefix):
if s.startswith(prefix):
return s[len(prefix):]
return s

and not raise an exception if the prefix/suffix doesn't match.
Though in this case your use case is not made any simpler.
Indeed it's uglier with either

newpath = path.lchop3("html/")
if newpath == path
newpath = path.lchop3("text/")
if newpath == path:
...

or

if path.startswith("html/"):
path = path.lstrip("html/")
elif path.startswith("text/"):
path = path.lstrip("text/")
...

I tried finding an example in the stdlib of code that would be
improved with your proposal. Here's something that would not
be improved, from mimify.py (it was the first grep hit I
looked at)

if prefix and line[:len(prefix)] == prefix:
line = line[len(prefix):]
pref = prefix
else:
pref = ''

In your version it would be:

if prefix:
try:
line = line.rstrip(prefix)
except TheException:
pref = ''
else:
pref = prefix
else:
pref = ''

which is longer than the original.

From pickle.py (grepping for 'endswith(' and a context of 2)

pickle.py- if ashex.endswith('L'):
pickle.py: ashex = ashex[2:-1]
pickle.py- else:
pickle.py: ashex = ashex[2:]

this would be better with my '3' variant, as

ashex = ashex.rchop3('L')[2:]

while your version would have to be

try:
ashex = ashex.rchomp('L')[2:]
except SomeException:
ashex = ashex[2:]
Even with my '2' version it's the simpler

ashex = (ashex.rchop2('L') or ashex)[2:]

The most common case will be for something like this

tarfile.py- if self.name.endswith(".gz"):
tarfile.py- self.name = self.name[:-3]

My "3" code handles it best

self.name = self.name.rstrip3(".gz")

Because your code throws an exception for what isn't
really an exceptional case it in essence needlessly
requires try/except/else logic instead of the simpler
if/elif logic.
Does anyone else find this to be a common need? Has this been suggested
before?


To summarize:
- I don't think it's needed that often
- I don't think your implementation's behavior (using an
exception) is what people would expect
- I don't think it does what you expect

Andrew
da***@dalkescientific.com

Jul 19 '05 #2
On Mon, 13 Jun 2005 07:05:39 +0000, Andy wrote:
What do people think of this?

'prefixed string'.lchop('prefix') == 'ed string'
'string with suffix'.rchop('suffix') == 'string with '
'prefix and suffix.chop('prefix', 'suffix') == ' and '

The names are analogous to strip, rstrip, and lstrip.
If chop is analogous to strip, then they shouldn't raise exceptions if the
strings do not start with the prefix or suffix.
I get tired of writing stuff like:

if path.startswith('html/'):
path = path[len('html/'):]
elif s.startswith('text/'):
path = path[len('text/'):]

It just gets tedious, and there is duplication. Instead I could just write:


Any time you are writing the same piece of code over and over again, you
should refactor it out as a function in your module, or even in a special
"utility functions" module:

def lchop(s, prefix):
if s.startswith(prefix): return s[len(prefix):]
raise ValueError("Substring doesn't begin with prefix.")
# or just return s if you prefer

and then call them whenever you need them.
--
Steven.

Jul 19 '05 #3
[Andrew Dalke]
<200 lines of thorough analysis>
To summarize:
- I don't think it's needed that often
- I don't think your implementation's behavior (using an
exception) is what people would expect
- I don't think it does what you expect


Wow, that was a remarkably thoughtful, total demolition ;-)
I expect that this thread is going to be somewhat short lived.

Jul 19 '05 #4
Andy wrote:
What do people think of this?

'prefixed string'.lchop('prefix') == 'ed string'
'string with suffix'.rchop('suffix') == 'string with '
'prefix and suffix.chop('prefix', 'suffix') == ' and '

The names are analogous to strip, rstrip, and lstrip. But the functionality
is basically this:

def lchop(self, prefix):
assert self.startswith(prefix)
return self[len(prefix):]

def rchop(self, suffix):
assert self.endswith(suffix)
return self[:-len(suffix]

def chop(self, prefix, suffix):
assert self.startswith(prefix)
assert self.endswith(suffix)
return self[len(prefix):-len(suffix]

The assert can be a raise of an appropriate exception instead. I find this
to be a very common need,
I'm not sure whether I should be surprised or not. I've never felt the
need for such a gadget. I don't even recall seeing such a gadget in
other languages. One normally either maintains a cursor (index or
pointer) without chopping up the original text, or splits the whole text
up into tokens. AFAICT, most simple needs in Python are satisfied by
str.split or re.split. For the special case of file paths, see
os.path.split*. There are also various 3rd party parsing modules -- look
in PyPI.

and often newbies assume that the
strip/lstrip/rstrip family behaves like this, but of course they don't.

I get tired of writing stuff like:

if path.startswith('html/'):
path = path[len('html/'):]
elif s.startswith('text/'):
path = path[len('text/'):]

So create a function (example below) and put it along with others in a
module called (say) andyutils.py ...

def chop_known_prefixes(path, prefixes):
for prefix in prefixes:
if path.startswith(prefix):
return path[len(prefix):]
return path

By the way, what do you do if path doesn't start with one of the "known"
prefixes?
It just gets tedious, and there is duplication. Instead I could just write:

try:
path = path.lchop('html/')
path = path.lchop('text/')
except SomeException:
pass

In the event that path contains (say) 'html/text/blahblah...', this
produces 'blahblah...'; the original tedious stuff produces
'text/blahblah...'.
Does anyone else find this to be a common need? Has this been suggested
before?


You can answer that last question yourself by googling comp.lang.python ...
Jul 19 '05 #5

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

Similar topics

3
by: Paul Kirby | last post by:
Hello All I am trying to create a function that returns a string like the following: // defined in headerfile // void test_func(char *retstr); // -------------------- // // c/cpp File //
51
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct...
35
by: jacob navia | last post by:
Hi guys! I like C because is fun. So, I wrote this function for the lcc-win32 standard library: strrepl. I thought that with so many "C heads" around, maybe we could improve it in a...
25
by: lovecreatesbeauty | last post by:
Hello experts, I write a function named palindrome to determine if a character string is palindromic, and test it with some example strings. Is it suitable to add it to a company/project library...
5
by: PaulH | last post by:
I have a function that is stripping off some XML from a configuration file. But, when I do a search for the pieces I want to strip, the std::string::find() function always returns std::string::npos...
6
by: bugnthecode | last post by:
I'm writing a program to send data over the serial port. I'm using pyserial, and I'm on WindowsXP. When I use literals I can get the data accross how I want it for example: 1 2 3 4...
5
by: Henrik | last post by:
The problem is (using MS Access 2003) I am unable to retrieve long strings (255 chars) from calculated fields through a recordset. The data takes the trip in three phases: 1. A custom public...
6
by: Andrea | last post by:
Hi, suppose that I have a string that is an hexadecimal number, in order to print this string I have to do: void print_hex(unsigned char *bs, unsigned int n){ int i; for (i=0;i<n;i++){...
25
by: Bala2508 | last post by:
Hi, I have a C++ application that extensively uses std::string and std::ostringstream in somewhat similar manner as below std::string msgHeader; msgHeader = "<"; msgHeader += a; msgHeader...
22
by: MLH | last post by:
100 Dim db As Database, rst As Recordset 120 Set db = CurrentDb 140 PString = "SELECT qryBatchList.ReadyFor906, qryBatchList.BatchID FROM qryBatchList WHERE...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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,...
1
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...
0
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...
0
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 ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.