split a string and build tuple

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

    split a string and build tuple

    hello,

    i'm looking for a pythonic and obvious way to do the following :

    having a string space separated like : s = "w1 w2 w3 w4 w5 w6 w7 w8..."
    how to get : l = (('w1', 'w2', 'w3'), ('w4', 'w5', 'w6'), ('w7', 'w8', ...),
    ....) ?
    (a kind of splitting and grouping in an elegant way)

    i think that list comprehension or "zip" could maybe help but i just can't
    get it work,

    thanks.


  • Lou Pecora

    #2
    Re: split a string and build tuple

    In article <4022acc0$0$295 9$626a54ce@news .free.fr>,
    "GrelEns" <grelens@NOSPAM yahoo.NOTNEEDED fr> wrote:
    [color=blue]
    > hello,
    >
    > i'm looking for a pythonic and obvious way to do the following :
    >
    > having a string space separated like : s = "w1 w2 w3 w4 w5 w6 w7 w8..."
    > how to get : l = (('w1', 'w2', 'w3'), ('w4', 'w5', 'w6'), ('w7', 'w8', ...),
    > ...) ?
    > (a kind of splitting and grouping in an elegant way)
    >
    > i think that list comprehension or "zip" could maybe help but i just can't
    > get it work,
    >
    > thanks.[/color]

    Since it is space-separated use the Python function 'split' to get a
    list of the separate "words." Then you can group them however you like
    using list functions.

    --
    -- Lou Pecora
    My views are my own.

    Comment

    • Jonathan Daugherty

      #3
      Re: split a string and build tuple

      # having a string space separated like : s = "w1 w2 w3 w4 w5 w6 w7 w8..."
      # how to get : l = (('w1', 'w2', 'w3'), ('w4', 'w5', 'w6'), ('w7', 'w8', ...),
      # ...) ?
      # (a kind of splitting and grouping in an elegant way)
      [color=blue][color=green][color=darkred]
      >>> import string
      >>> s = "w1 w2 w3 w4 w5 w6 w7 w8"
      >>> x = string.split(s)
      >>> x[/color][/color][/color]
      ['w1', 'w2', 'w3', 'w4', 'w5', 'w6', 'w7', 'w8'][color=blue][color=green][color=darkred]
      >>> for index in range(0, len(x), 3):[/color][/color][/color]
      .... print x[index:index + 3]
      ....
      ['w1', 'w2', 'w3']
      ['w4', 'w5', 'w6']
      ['w7', 'w8']

      --

      Jonathan Daugherty


      "It's a book about a Spanish guy called Manual, you should read it."
      -- Dilbert

      Comment

      Working...