473,569 Members | 2,729 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Behaviour of str.split

Hi,

I'm curious about the behaviour of the str.split() when applied to empty
strings.

"".split() returns an empty list, however..

"".split("* ") returns a list containing one empty string.

I would have expected the second example to have also returned an empty
list. What am I missing?
TIA,

Will McGugan
--
http://www.willmcgugan.com
"".join( [ {'*':'@','^':'. '}.get(c,None) or chr(97+(ord(c)-84)%26) for c
in "jvyy*jvyyzptht na^pbz" ] )
Jul 19 '05 #1
9 4336
The behaviour of "".split("* ") is not that strange as the splitpoint
always disappear. The re.split() have a nice option to keep the
splitpoint which the str.split should have, I think.

One expectation I keep fighting within myself is that I expect

"mystring".spli t('') to return ['m', 'y', 's', 't', 'r', 'i', 'n',
'g']. But I guess it's in line with "There should be one-- and
preferably only one --obvious way to do it." that it's not so.

Jul 19 '05 #2

runes wrote:
The behaviour of "".split("* ") is not that strange as the splitpoint
always disappear. The re.split() have a nice option to keep the
splitpoint which the str.split should have, I think.

One expectation I keep fighting within myself is that I expect

"mystring".spli t('') to return ['m', 'y', 's', 't', 'r', 'i', 'n',
'g']. But I guess it's in line with "There should be one-- and
preferably only one --obvious way to do it." that it's not so.


Fortunately, this is easy to write as: list("mystring" ).
Actually for me it's not so counter-intuitive that "mystring".spli t('')
doesn't work; what are you trying to split on?

Anyways, I usually need to split on something more complicated so I
split with regexes, usually.

cheers,

--Tim

Jul 19 '05 #3
[Tim N. van der Leeuw]
Fortunately, this is easy to write as: list("mystring" ).


Sure, and map(None, "mystring")

Anyways, I have settled with this bevaviour, more or less ;-)

Rune

Jul 19 '05 #4
On Mon, 18 Apr 2005 16:16:00 +0100, Will McGugan
<ne**@NOwillmcg uganSPAM.com> wrote:
Hi,

I'm curious about the behaviour of the str.split() when applied to empty
strings.

"".split() returns an empty list, however..

"".split("*" ) returns a list containing one empty string.

I would have expected the second example to have also returned an empty
list. What am I missing?


You are missing a perusal of the documentation. Had you done so, you
would have noticed that the actual behaviour that you mentioned is
completely the reverse of what is in the documentation!

"""
Splitting an empty string with a specified separator returns an empty
list.
If sep is not specified or is None, a different splitting algorithm is
applied. <snip> Splitting an empty string or a string consisting of
just whitespace will return "['']".
"""

As you stumbled on this first, you may have the honour of submitting a
patch to the docs and getting your name on the roll of contributors.
Get in quickly, before X** L** does :-)

Cheers,

John
Jul 19 '05 #5
[Will McGugan]
I'm curious about the behaviour of the str.split() when applied to empty
strings.

"".split() returns an empty list, however..

"".split("*" ) returns a list containing one empty string.

[John Machin] You are missing a perusal of the documentation. Had you done so, you
would have noticed that the actual behaviour that you mentioned is
completely the reverse of what is in the documentation!


Nuts! I've got it from here and will get it fixed up.

<lament>
str.split() has to be one of the most frequently revised pieces of
documentation. In this case, the two statements about splitting empty strings
need to be swapped. Previously, all the changes occured because
someone/somewhere would always find a way to misread whatever was there.

In the absence of reading the docs, a person's intuition seems to lead them to
guess that the behavior will be different than it actually is. Unfortunately,
one person's intuition is often at odds with another's.
</lament>
Raymond Hettinger
Jul 19 '05 #6
Will McGugan wrote:
Hi,

I'm curious about the behaviour of the str.split() when applied to empty
strings.

"".split() returns an empty list, however..

"".split("* ") returns a list containing one empty string.


Both of these make sense as limiting cases.

Consider
"a b c".split() ['a', 'b', 'c'] "a b".split() ['a', 'b'] "a".split() ['a'] "".split() []

and
"**".split( "*") ['', '', ''] "*".split(" *") ['', ''] "".split("* ")

['']

The split() method is really doing two somewhat different things
depending on whether it is given an argument, and the end-cases
come out differently.

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 19 '05 #7
Greg Ewing wrote:
Will McGugan wrote:
Hi,

I'm curious about the behaviour of the str.split() when applied to
empty strings.

"".split() returns an empty list, however..

"".split("* ") returns a list containing one empty string.

Both of these make sense as limiting cases.

Consider
>>> "a b c".split() ['a', 'b', 'c'] >>> "a b".split() ['a', 'b'] >>> "a".split() ['a'] >>> "".split() []

and
>>> "**".split( "*") ['', '', ''] >>> "*".split(" *") ['', ''] >>> "".split("* ") ['']

The split() method is really doing two somewhat different things
depending on whether it is given an argument, and the end-cases
come out differently.

You don't really explain *why* they make sense as limiting cases, as
your examples are quite different.

Consider
"a*b*c".split(" *") ['a', 'b', 'c'] "a*b".split("*" ) ['a', 'b'] "a".split(" *") ['a'] "".split("* ")

['']

Now how is this logical when compared with split() above?

David
Jul 19 '05 #8
On Wed, 20 Apr 2005 10:55:18 +0200, David Fraser <da****@sjsoft. com> wrote:
Greg Ewing wrote:
Will McGugan wrote:
Hi,

I'm curious about the behaviour of the str.split() when applied to
empty strings.

"".split() returns an empty list, however..

"".split("* ") returns a list containing one empty string.

Both of these make sense as limiting cases.

Consider
>>> "a b c".split()

['a', 'b', 'c']
>>> "a b".split()

['a', 'b']
>>> "a".split()

['a']
>>> "".split()

[]

and
>>> "**".split( "*")

['', '', '']
>>> "*".split(" *")

['', '']
>>> "".split("* ")

['']

The split() method is really doing two somewhat different things
depending on whether it is given an argument, and the end-cases
come out differently.

You don't really explain *why* they make sense as limiting cases, as
your examples are quite different.

Consider
"a*b*c".split(" *")['a', 'b', 'c'] "a*b".split("*" )['a', 'b'] "a".split(" *")['a'] "".split("* ")['']

Now how is this logical when compared with split() above?


The trouble is that s.split(arg) and s.split() are two different functions.

The first is 1:1 and reversible like arg.join(s.spli t(arg))==s
The second is not 1:1 nor reversible: '<<various whitespace>>'.j oin(s.split()) == s ?? Not usually.

I think you can do it with the equivalent whitespace regex, preserving the splitout whitespace
substrings and ''.joining those back with the others, but not with split(). I.e.,
def splitjoin(s, splitter=None): ... return (splitter is None and '<<whitespace>> ' or splitter).join( s.split(splitte r))
... splitjoin('a*b* c', '*') 'a*b*c' splitjoin('a*b' , '*') 'a*b' splitjoin('a', '*') 'a' splitjoin('', '*') '' splitjoin('a b c') 'a<<whitespace> >b<<whitespace> >c' splitjoin('a b ') 'a<<whitespace> >b' splitjoin(' b ') 'b' splitjoin('') ''
splitjoin('**** *','*') '*****'
Note why that works:
'*****'.split(' *') ['', '', '', '', '', ''] '*a'.split('*') ['', 'a'] 'a*'.split('*') ['a', '']
splitjoin('*a', '*') '*a' splitjoin('a*', '*')

'a*'

Regards,
Bengt Richter
Jul 19 '05 #9
Bengt Richter wrote:
On Wed, 20 Apr 2005 10:55:18 +0200, David Fraser <da****@sjsoft. com> wrote:

Greg Ewing wrote:
Will McGugan wrote:
Hi,

I'm curious about the behaviour of the str.split() when applied to
empty strings.

"".split( ) returns an empty list, however..

"".split("* ") returns a list containing one empty string.
Both of these make sense as limiting cases.

Consider

>>> "a b c".split()
['a', 'b', 'c']
>>> "a b".split()
['a', 'b']
>>> "a".split()
['a']
>>> "".split()
[]

and

>>> "**".split( "*")
['', '', '']
>>> "*".split(" *")
['', '']
>>> "".split("* ")
['']

The split() method is really doing two somewhat different things
depending on whether it is given an argument, and the end-cases
come out differently.


You don't really explain *why* they make sense as limiting cases, as
your examples are quite different.

Consider
>"a*b*c".sp lit("*")


['a', 'b', 'c']
>"a*b".spli t("*")


['a', 'b']
>"a".split( "*")


['a']
>"".split(" *")


['']

Now how is this logical when compared with split() above?

The trouble is that s.split(arg) and s.split() are two different functions.

The first is 1:1 and reversible like arg.join(s.spli t(arg))==s
The second is not 1:1 nor reversible: '<<various whitespace>>'.j oin(s.split()) == s ?? Not usually.

I think you can do it with the equivalent whitespace regex, preserving the splitout whitespace
substrings and ''.joining those back with the others, but not with split(). I.e.,
>>> def splitjoin(s, splitter=None): ... return (splitter is None and '<<whitespace>> ' or splitter).join( s.split(splitte r))
... >>> splitjoin('a*b* c', '*') 'a*b*c' >>> splitjoin('a*b' , '*') 'a*b' >>> splitjoin('a', '*') 'a' >>> splitjoin('', '*') '' >>> splitjoin('a b c') 'a<<whitespace> >b<<whitespace> >c' >>> splitjoin('a b ') 'a<<whitespace> >b' >>> splitjoin(' b ') 'b' >>> splitjoin('') ''
>>> splitjoin('**** *','*') '*****'
Note why that works:
>>> '*****'.split(' *') ['', '', '', '', '', ''] >>> '*a'.split('*') ['', 'a'] >>> 'a*'.split('*') ['a', '']
>>> splitjoin('*a', '*') '*a' >>> splitjoin('a*', '*')

'a*'


Thanks, this makes sense.
So ideally if we weren't dealing with backward compatibility these
functions might have different names... "split" (with arg) and
"spacesplit " (without arg)
In fact it would be nice to allow an argument to "spacesplit " specifying
the characters regarded as 'space'
But all not worth breaking current code :-)

David
Jul 19 '05 #10

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

Similar topics

7
2002
by: Timothy Madden | last post by:
Hello all I'm trying to include some files in an included file. Think of some scripts like this /index.php /scripts/logging.php /scripts/config.php /scripts/db_access.php
4
1462
by: bill | last post by:
Consider: >>> import shlex >>> shlex.split('$(which sh)') Is this behavior correct? It seems that I should either get one token, or the list , but certainly breaking it the way it does is erroneous.
4
1526
by: Tim Streater | last post by:
I have this: splitter = //; dateItems = dateString.split (splitter, 3); where dateString might contain such as 3.4.5 or 3/4/5 or 3-4-5. But it might also be nullstring or any junk the user types in. Now I find that with the code above, and a null string, .split gives up and I get a JavaScript error, instead of what I might expect...
8
1894
by: Steven D'Aprano | last post by:
I came across this unexpected behaviour of getattr for new style classes. Example: >>> class Parrot(object): .... thing = .... >>> getattr(Parrot, "thing") is Parrot.thing True >>> getattr(Parrot, "__dict__") is Parrot.__dict__ False
2
1656
by: Adam Honek | last post by:
I have the following code below. The thing is, even if txtCCEmailAddress.Text is empty (no text), CCRecipeant will return a Ubound() higher than 0 and still go in the loop. If there's nothing to split how can CCRecipeant be a positive UBound value? 'Get the number of specified CC recipeants CCRecipeant = txtCCEmailAddress.Text.Split(";")
9
1781
by: horizon5 | last post by:
Hi, my collegues and I recently held a coding style review. All of the code we produced is used in house on a commerical project. One of the minor issues I raised was the common idiom of specifing: <pre> if len(x) 0: do_something() </pre>
7
2769
by: Andrew McLean | last post by:
I have a bunch of csv files that have the following characteristics: - field delimiter is a comma - all fields quoted with double quotes - lines terminated by a *space* followed by a newline What surprised me was that the csv reader included the trailing space in the final field value returned, even though it is outside of the quotes.
3
1556
by: Walter Cruz | last post by:
Hi all! Just a simple question about the behaviour of a regex in python. (I discussed this on IRC, and they suggest me to post here). I tried to split the string "walter ' cruz" using \b . In ruby, it returns: irb(main):001:0>"walter ' cruz".split(/\b/)
5
1550
by: Steve | last post by:
I understand that string.split() should produce an array from a string. However when I use the following script the type of the result is indeed an object but the array elements are undefined. Why? var strTest = '1,2,3,4'; var aryTest = strTest.split(); alert(typeof aryTest + " " + aryTest); Thanks in advance.
0
7694
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...
0
7921
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. ...
0
7964
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...
0
6278
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...
1
5504
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...
0
3651
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...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
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
0
936
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...

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.