473,747 Members | 2,260 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

new string method in 2.5 (partition)

Forgive my excitement, especially if you are already aware of this, but
this seems like the kind of feature that is easily overlooked (yet could
be very useful):
Both 8-bit and Unicode strings have new partition(sep) and
rpartition(sep) methods that simplify a common use case.
The find(S) method is often used to get an index which is then used to
slice the string and obtain the pieces that are before and after the
separator. partition(sep) condenses this pattern into a single method
call that returns a 3-tuple containing the substring before the
separator, the separator itself, and the substring after the separator.
If the separator isn't found, the first element of the tuple is the
entire string and the other two elements are empty. rpartition(sep) also
returns a 3-tuple but starts searching from the end of the string; the
"r" stands for 'reverse'.

Some examples:

>>('http://www.python.org' ).partition('://')
('http', '://', 'www.python.org ')
>>('file:/usr/share/doc/index.html').pa rtition('://')
('file:/usr/share/doc/index.html', '', '')
>>(u'Subject: a quick question').part ition(':')
(u'Subject', u':', u' a quick question')
>>'www.python.o rg'.rpartition( '.')
('www.python', '.', 'org')
>>'www.python.o rg'.rpartition( ':')
('', '', 'www.python.org ')

(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)
Sep 19 '06 #1
25 12949
sweet thanks for the heads up.

John Salerno wrote:
Forgive my excitement, especially if you are already aware of this, but
this seems like the kind of feature that is easily overlooked (yet could
be very useful):
Both 8-bit and Unicode strings have new partition(sep) and
rpartition(sep) methods that simplify a common use case.
The find(S) method is often used to get an index which is then used to
slice the string and obtain the pieces that are before and after the
separator. partition(sep) condenses this pattern into a single method
call that returns a 3-tuple containing the substring before the
separator, the separator itself, and the substring after the separator.
If the separator isn't found, the first element of the tuple is the
entire string and the other two elements are empty. rpartition(sep) also
returns a 3-tuple but starts searching from the end of the string; the
"r" stands for 'reverse'.

Some examples:

>>('http://www.python.org' ).partition('://')
('http', '://', 'www.python.org ')
>>('file:/usr/share/doc/index.html').pa rtition('://')
('file:/usr/share/doc/index.html', '', '')
>>(u'Subject: a quick question').part ition(':')
(u'Subject', u':', u' a quick question')
>>'www.python.o rg'.rpartition( '.')
('www.python', '.', 'org')
>>'www.python.o rg'.rpartition( ':')
('', '', 'www.python.org ')

(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)
Sep 19 '06 #2
I'm confused.
What's the difference between this and string.split?

John Salerno wrote:
Forgive my excitement, especially if you are already aware of this, but
this seems like the kind of feature that is easily overlooked (yet could
be very useful):
Both 8-bit and Unicode strings have new partition(sep) and
rpartition(sep) methods that simplify a common use case.
The find(S) method is often used to get an index which is then used to
slice the string and obtain the pieces that are before and after the
separator. partition(sep) condenses this pattern into a single method
call that returns a 3-tuple containing the substring before the
separator, the separator itself, and the substring after the separator.
If the separator isn't found, the first element of the tuple is the
entire string and the other two elements are empty. rpartition(sep) also
returns a 3-tuple but starts searching from the end of the string; the
"r" stands for 'reverse'.

Some examples:

>>('http://www.python.org' ).partition('://')
('http', '://', 'www.python.org ')
>>('file:/usr/share/doc/index.html').pa rtition('://')
('file:/usr/share/doc/index.html', '', '')
>>(u'Subject: a quick question').part ition(':')
(u'Subject', u':', u' a quick question')
>>'www.python.o rg'.rpartition( '.')
('www.python', '.', 'org')
>>'www.python.o rg'.rpartition( ':')
('', '', 'www.python.org ')

(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)
Sep 19 '06 #3
ri************@ gmail.com <ri************ @gmail.comwrote :
What's the difference between this and string.split?
>>('http://www.python.org' ).partition('://')
('http', '://', 'www.python.org ')
>>('http://www.python.org' ).split('://')
['http', 'www.python.org ']

--
Lawrence - http://www.oluyede.org/blog
"Nothing is more dangerous than an idea
if it's the only one you have" - E. A. Chartier
Sep 19 '06 #4
ri************@ gmail.com wrote:
I'm confused.
What's the difference between this and string.split?
>>s = 'hello, world'
>>s.split(',' )
['hello', ' world']
>>s.partition(' ,')
('hello', ',', ' world')
split returns a list of the substrings on either side of the specified
argument.

partition returns a tuple of the substring on the left of the argument,
the argument itself, and the substring on the right. rpartition reads
from right to left.
But you raise a good point. Notice this:
>>s = 'hello, world, how are you'
>>s.split(',' )
['hello', ' world', ' how are you']
>>s.partition(' ,')
('hello', ',', ' world, how are you')

split will return all substrings. partition (and rpartition) only return
the substrings before and after the first occurrence of the argument.
Sep 19 '06 #5
John Salerno a écrit :
Forgive my excitement, especially if you are already aware of this, but
this seems like the kind of feature that is easily overlooked (yet could
be very useful):
Both 8-bit and Unicode strings have new partition(sep) and
rpartition(sep) methods that simplify a common use case.
The find(S) method is often used to get an index which is then used to
slice the string and obtain the pieces that are before and after the
separator.
Err... is it me being dumb, or is it a perfect use case for str.split ?
partition(sep) condenses this pattern into a single method
call that returns a 3-tuple containing the substring before the
separator, the separator itself, and the substring after the separator.
If the separator isn't found, the first element of the tuple is the
entire string and the other two elements are empty. rpartition(sep) also
returns a 3-tuple but starts searching from the end of the string; the
"r" stands for 'reverse'.

Some examples:

>>('http://www.python.org' ).partition('://')
('http', '://', 'www.python.org ')
>>('file:/usr/share/doc/index.html').pa rtition('://')
('file:/usr/share/doc/index.html', '', '')
>>(u'Subject: a quick question').part ition(':')
(u'Subject', u':', u' a quick question')
>>'www.python.o rg'.rpartition( '.')
('www.python', '.', 'org')
>>'www.python.o rg'.rpartition( ':')
('', '', 'www.python.org ')
I must definitively be dumb, but so far I fail to see how it's better
than split and rsplit:
>>'http://www.python.org' .split('://')
['http', 'www.python.org ']
>>'file:/usr/share/doc/index.html'.spl it('://')
['file:/usr/share/doc/index.html']
>>u'Subject: a quick question'.split (': ')
[u'Subject', u'a quick question']
>>u'Subject: a quick question'.rspli t(': ')
[u'Subject', u'a quick question']
>>'www.python.o rg'.rsplit('.', 1)
['www.python', 'org']
>>>
There are IMVHO much exciting new features in 2.5 (enhanced generators,
try/except/finally, ternary operator, with: statement etc...)
Sep 19 '06 #6
>partition(se p) condenses this pattern into a single method
>call that returns a 3-tuple containing the substring before
the separator, the separator itself, and the substring after
the separator. If the separator isn't found, the first
element of the tuple is the entire string and the other two
elements are empty. rpartition(sep) also returns a 3-tuple
but starts searching from the end of the string; the "r"
stands for 'reverse'.

I'm confused. What's the difference between this and
string.split?
(please don't top-post...I've inverted and trimmed for the sake
of readability)

I too am a bit confused but I can see uses for it, and there
could be good underlying reason to do as much. Split doesn't
return the separator. It's also guarnteed to return a 3-tuple. E.g.
>>s1 = 'one'
s2 = 'one|two'
len(s1.split( '|', 1)
1
>>len(s2.split( '|', 1))
2

which could make a difference when doing tuple-assignment:
>>v1, v2 = s2.split('|', 1)
# works fine
v1, v2 = s1.split('|', 1)
[traceback]

whereas one could consistently do something like
>>v1, _, v2 = s1.partition('| ')
without fear of a traceback to deal with.

Just a few thoughts...

-tkc

Sep 19 '06 #7
But you raise a good point. Notice this:
>
>>s = 'hello, world, how are you'
>>s.split(',' )
['hello', ' world', ' how are you']
>>s.partition(' ,')
('hello', ',', ' world, how are you')

split will return all substrings. partition (and rpartition) only return
the substrings before and after the first occurrence of the argument.
The split()/rsplit() functions do take an optional argument for
the maximum number of splits to make, just FYI...
>>help("".split )
Help on built-in function split:

split(...)
S.split([sep [,maxsplit]]) -list of strings

Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator.

(as I use this on a regular basis when mashing up various text
files in a data conversion process)

-tkc


Sep 19 '06 #8
Bruno Desthuilliers wrote:
Err... is it me being dumb, or is it a perfect use case for str.split ?
Hmm, I suppose you could get nearly the same functionality as using
split(':', 1), but with partition you also get the separator returned as
well.
There are IMVHO much exciting new features in 2.5 (enhanced generators,
try/except/finally, ternary operator, with: statement etc...)
I definitely agree, but I figure everyone knows about those already.
There are also the startswith() and endswith() string methods that are
new and seem neat as well.
Sep 19 '06 #9
John Salerno schrieb:
Bruno Desthuilliers wrote:
>Err... is it me being dumb, or is it a perfect use case for str.split ?

Hmm, I suppose you could get nearly the same functionality as using
split(':', 1), but with partition you also get the separator returned as
well.
Well, x.split(":", 1) returns a list of one or two elements, depending on x,
while x.partition(":" ) always returns a three-tuple.

Thomas

Sep 19 '06 #10

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

Similar topics

0
2635
by: Connelly Barnes | last post by:
Yet another useful code snippet! This StringBuffer class is a FIFO for character data. Example: B = StringBuffer('Hello W') B.append('orld!') print B.read(5) # 'Hello' print B.read() # 'World!'
108
6438
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
5
1599
by: ikshefem | last post by:
I often need to re-code for myself a small code snippet to define string.upto() and string.from(), which are used like : # canonical examples > "1234456789".upto("45") '1234' > "123456dd987".from('d') 'd987' # if not found, return whole string
5
5950
by: sameer_deshpande | last post by:
Hi, I need to create a partition table but the column on which I need to create a partition may not have any logical ranges. So while creating or defining partition function I can not use any range. like CREATE PARTITION FUNCTION my_part_func (NUMERIC(7)) AS RANGE LEFT FOR VALUES (1,100,1000);
8
5041
by: girish | last post by:
Hi, I want to generate all non-empty substrings of a string of length >=2. Also, each substring is to be paired with 'string - substring' part and vice versa. Thus, gives me , , , , , ] etc. Similarly, 'abcd' should give me , , , , , ,, , , , , , ,] I've tried the following but i cant prevent duplicates and i'm missing
1
4966
by: Laurence | last post by:
Hi folks, As I konw: database partition (aka data partition?), the database can span multiple machines; table partition, the data within a table can seperate by certain condition. How about inter-partition and intra-partition? Is inter-partition database partition...?
0
12978
by: Vinod Sadanandan | last post by:
Table Partition Performance analysis ============================================ Collection of Statistics for Cost-Based Optimization/DBMS_STATS vs. ANALYZE The cost-based approach relies on statistics and if the cost-based Approach is used , then statistics should be gernerated for all tables, clusters, and all types of indexes accessed by SQL statements. If the size and data distribution of your tables change frequently, then...
0
3786
debasisdas
by: debasisdas | last post by:
SAMPLE CODE TO CREATE SUB PARTITIONS ======================================= RANGE-HASH-9i ------------------------- CREATE TABLE SUBPART ( ID NUMBER(10) PRIMARY KEY, NAME VARCHAR2(20) )
0
3425
debasisdas
by: debasisdas | last post by:
USING PARTITION =================== PARTITION BY RANGE-as per Oracle 8 -------------------------------------- CREATE TABLE RANGEPART ( ID NUMBER(2) PRIMARY KEY, NAME VARCHAR2(20) )
0
8979
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
8818
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
9522
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
9307
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
8234
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
6790
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
6069
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
4589
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
3296
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

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.