473,785 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ 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('pr efix', '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(s uffix)
return self[:-len(suffix]

def chop(self, prefix, suffix):
assert self.startswith (prefix)
assert self.endswith(s uffix)
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('t ext/'):
path = path[len('text/'):]

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

try:
path = path.lchop('htm l/')
path = path.lchop('tex t/')
except SomeException:
pass

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

Andy
Jul 19 '05 #1
4 2216
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('pr efix', 'suffix') == ' and '
Your use case is
I get tired of writing stuff like:

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

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

try:
path = path.lchop('htm l/')
path = path.lchop('tex t/')
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(pr efix):
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(pr efix):
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("ht ml/")
if newpath == path
newpath = path.lchop3("te xt/")
if newpath == path:
...

or

if path.startswith ("html/"):
path = path.lstrip("ht ml/")
elif path.startswith ("text/"):
path = path.lstrip("te xt/")
...

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(pre fix)
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.endsw ith(".gz"):
tarfile.py- self.name = self.name[:-3]

My "3" code handles it best

self.name = self.name.rstri p3(".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***@dalkescie ntific.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('pr efix', '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('t ext/'):
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(pr efix): return s[len(prefix):]
raise ValueError("Sub string 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('pr efix', '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(s uffix)
return self[:-len(suffix]

def chop(self, prefix, suffix):
assert self.startswith (prefix)
assert self.endswith(s uffix)
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('t ext/'):
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_pref ixes(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('htm l/')
path = path.lchop('tex t/')
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.pytho n ...
Jul 19 '05 #5

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

Similar topics

3
1681
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
8296
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 code? many thx!
35
5836
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 collective brainstorming session. Let's discuss some C here, for a change :-)
25
6549
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 as a small tool function according to its quality? I will be very happy to get your suggestion from every aspect on it: interface design, C language knowledge or algorithm efficient. Sincerely,
5
4615
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 (-1). I can print out the config string at the beginning of CleanCfgFile(), and the strings are there exactly the way I'm looking for them. So, the question is, what am I doing wrong? Function() {
6
1721
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 6 serialport.write('!SC'+'\x01'+'\x05'+'\xFA'+'\x00'+'\r') 1=Get devices attention 2=Select channel on device 3=Rate for movement
5
5888
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 function returns a long string. This works. 2. A query has a calculated field based on the custom function above. This works when the query is run directly.
6
14714
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++){ printf("%02x",bs); } }
25
8386
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
10297
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 qryBatchList.BatchID=GetCurrentBatchID()" 160 Set rst = db.OpenRecordset(PString, dbOpenDynaset) At compile time, things are OK. But at run time, line #160 gives rise to an error saying some FN I've used for years is undefined. It almost seems like it pukes on some random
0
9645
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
9481
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
10155
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10095
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
9953
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6741
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();...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4054
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
2881
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.