string.split bug?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • MetalOne

    string.split bug?

    string.split("" ) ==> []
    string.split("" ,",") ==> ['']

    I did not expect these to have different outputs.

    I have a string with comma delimited numbers.
    There can be zero or more numbers in the string
    s = "0x41, 0x42"

    I wanted to do
    numbers = map(lambda x: int(x,16), string.split(s, ","))

    However, when there are no numbers, this generates an error.
  • Peter Otten

    #2
    Re: string.split bug?

    MetalOne wrote:
    [color=blue]
    > string.split("" ) ==> []
    > string.split("" ,",") ==> ['']
    >
    > I did not expect these to have different outputs.
    >
    > I have a string with comma delimited numbers.
    > There can be zero or more numbers in the string
    > s = "0x41, 0x42"
    >
    > I wanted to do
    > numbers = map(lambda x: int(x,16), string.split(s, ","))
    >
    > However, when there are no numbers, this generates an error.[/color]

    It's not a bug, it's a feature. The same question was asked on python-dev
    recently, and it turned out that str.split() and str.split(separ ator) are
    intended to work differently.

    A slightly modernized variant of your example could then be:
    [color=blue][color=green][color=darkred]
    >>> def numbers(s, sep=None):[/color][/color][/color]
    .... return [int(x, 16) for x in s.split(sep) if x]
    ....[color=blue][color=green][color=darkred]
    >>> numbers("aa bb cc\n")[/color][/color][/color]
    [170, 187, 204][color=blue][color=green][color=darkred]
    >>> numbers("aa,bb, cc", ",")[/color][/color][/color]
    [170, 187, 204][color=blue][color=green][color=darkred]
    >>> numbers("", ",")[/color][/color][/color]
    []

    Peter

    Comment

    • Erik Max Francis

      #3
      Re: string.split bug?

      MetalOne wrote:
      [color=blue]
      > string.split("" ) ==> []
      > string.split("" ,",") ==> ['']
      >
      > I did not expect these to have different outputs.[/color]

      S.split(None) is a special case which keys off of all whitespace, not
      just a single delimiter string. So when presented with an input string
      that contains nothing but whitespace, it strips everything and doesn't
      find any tokens at all.

      --
      __ Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
      / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
      \__/ Who, my friend, can scale Heaven?
      -- _The Epic of Gilgamesh_

      Comment

      Working...