Converting a string to an array?

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

    #1

    Converting a string to an array?

    While working on a Jumble-esque program, I was trying to get a
    string into a character array. Unfortunately, it seems to choke
    on the following

    import random
    s = "abcefg"
    random.shuffle( s)

    returning

    File "/usr/lib/python2.3/random.py", line 250, in shuffle
    x[i], x[j] = x[j], x[i]
    TypeError: object doesn't support item assignment

    The closest hack I could come up with was

    import random
    s = "abcdefg"
    a = []
    a.extend(s)
    random.shuffle( a)
    s = "".join(a)

    This lacks the beauty of most python code, and clearly feels like
    there's somethign I'm missing. Is there some method or function
    I've overlooked that would convert a string to an array with less
    song-and-dance? Thanks,

    -tim





  • Xavier Morel

    #2
    Re: Converting a string to an array?

    Tim Chase wrote:[color=blue]
    > The closest hack I could come up with was
    >
    > import random
    > s = "abcdefg"
    > a = []
    > a.extend(s)
    > random.shuffle( a)
    > s = "".join(a)
    >
    > This lacks the beauty of most python code, and clearly feels like
    > there's somethign I'm missing. Is there some method or function
    > I've overlooked that would convert a string to an array with less
    > song-and-dance? Thanks,
    >
    > -tim
    >[/color]

    Would
    [color=blue][color=green][color=darkred]
    >>> import random
    >>> s = "abcdefg"
    >>> data = list(s)
    >>> random.shuffle( data)
    >>> "".join(dat a)[/color][/color][/color]
    'bfegacd'[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    fit you better?

    Comment

    • Tim Chase

      #3
      gracefully handling broken pipes (was Re: Converting a string toan array?)

      > >>> import random[color=blue][color=green][color=darkred]
      > >>> s = "abcdefg"
      > >>> data = list(s)
      > >>> random.shuffle( data)
      > >>> "".join(dat a)[/color][/color]
      > 'bfegacd'
      >
      > fit you better?[/color]

      Excellent! Thanks. I kept trying to find something like an
      array() function. Too many languages, too little depth.

      The program was just a short script to scramble the insides of
      words to exercise word recognition, even when the word is mangled.

      It's amazing how little code it takes to get this working.

      When using it as a filter, if a downstream pipe (such as "head")
      cuts it off, I get an error:

      bash# ./scramble.py bigfile.txt | head -50

      [proper output here]

      Traceback (most recent call last):
      File "./scramble.py", line 11, in ?
      print r.sub(shuffleWo rd, line),
      IOError: [Errno 32] Broken pipe

      At the moment, I'm just wrapping the lot in a try/except block,
      and ignoring the error. Is there a better way to deal with this
      gracefully? If some more serious IO error occurred, it would be
      nice to not throw that baby out with the bath-water. Is there a
      way to discern a broken pipe from other IOError exceptions?

      Thanks again.

      -tim

      import random, sys, re
      r = re.compile("[A-Za-z][a-z]{3,}")
      def shuffleWord(mat chobj):
      s = matchobj.group( 0)
      a = list(s[1:-1])
      random.shuffle( a)
      return "".join([s[0], "".join(a), s[-1]])
      try:
      for line in sys.stdin.readl ines():
      print r.sub(shuffleWo rd, line),
      except IOError:
      pass




      Comment

      • Fredrik Lundh

        #4
        Re: gracefully handling broken pipes (was Re: Converting a stringtoan array?)

        Tim Chase wrote:
        [color=blue][color=green][color=darkred]
        > > >>> import random
        > > >>> s = "abcdefg"
        > > >>> data = list(s)
        > > >>> random.shuffle( data)
        > > >>> "".join(dat a)[/color]
        > > 'bfegacd'
        > >
        > > fit you better?[/color]
        >
        > Excellent! Thanks. I kept trying to find something like an
        > array() function. Too many languages, too little depth.[/color]
        [color=blue][color=green][color=darkred]
        >>> from array import array
        >>> a = array('c', "abcdefgh")
        >>> a[/color][/color][/color]
        array('c', 'abcdefgh')[color=blue][color=green][color=darkred]
        >>> import random
        >>> random.shuffle( a)
        >>> a[/color][/color][/color]
        array('c', 'gfecdabh')[color=blue][color=green][color=darkred]
        >>> a.tostring()[/color][/color][/color]
        'gfecdabh'

        </F>



        Comment

        • Bryan Olson

          #5
          Re: Converting a string to an array?

          Tim Chase wrote:[color=blue]
          > While working on a Jumble-esque program, I was trying to get a string
          > into a character array. Unfortunately, it seems to choke on the following
          >
          > import random
          > s = "abcefg"
          > random.shuffle( s)
          >
          > returning
          >
          > File "/usr/lib/python2.3/random.py", line 250, in shuffle
          > x[i], x[j] = x[j], x[i]
          > TypeError: object doesn't support item assignment[/color]

          Yes, Python has had that same problem elsewhere, notably the
          mutating methods 'sort' and 'reverse'. Those problems are now
          reasonably well solved. What's really neat is that the names
          of the new methods: 'sorted' and 'reversed', are adjectives
          describing the return values we want, where 'sort' and
          'reverse' are verbs, calling for procedures to be performed.


          For sorting, we had the procedure 'sort', then added the pure
          function 'sorted'. We had a 'reverse' procedure, and wisely
          added the 'reversed' function.

          Hmmm... what we could we possible do about 'shuffle'?


          --
          --Bryan

          Comment

          • Paul Rubin

            #6
            Re: Converting a string to an array?

            Tim Chase <python.list@ti m.thechases.com > writes:[color=blue]
            > The closest hack I could come up with was
            >
            > import random
            > s = "abcdefg"
            > a = []
            > a.extend(s)
            > random.shuffle( a)
            > s = "".join(a)[/color]

            You could use

            import random
            s = list("abcdefg")
            random.shuffle( s)
            s = "".join(s)

            which cuts down the clutter slightly.

            Comment

            • Tim Peters

              #7
              Re: Converting a string to an array?

              [Bryan Olson][color=blue]
              > ...
              > For sorting, we had the procedure 'sort', then added the pure
              > function 'sorted'. We had a 'reverse' procedure, and wisely
              > added the 'reversed' function.
              >
              > Hmmm... what we could we possible do about 'shuffle'?[/color]

              'permuted' is the obvious answer, but that would leave us open to more
              charges of hifalutin elitism, so the user-friendly and slightly risque
              'jiggled' it is.

              sorry-it-can't-be-'shuffled'-we-ran-out-of-'f's-ly y'rs - tim

              Comment

              Working...