Splitting strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Eyes Of Madness
    New Member
    • Mar 2008
    • 5

    Splitting strings

    I'm doing a program for a class of mine and I am having trouble splitting my strings up. I know you can do something like:

    a = '012345'
    a[0:3]
    returns 012

    but I am inputing strings of varying length and I cant just do the above notation. I need to split the string into groups of 3 in order to work. Any help would be much appreciated.
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You can use that notation, you just need to use a loop and probably the range function (docs here in the Python Library Reference). Or you could use the slice function from the same source.

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      Code:
      >>> import textwrap
      >>> s="123456"
      >>> textwrap.wrap(s,3)
      ['123', '456']

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        [code=Python]>>> import string
        >>> s = string.ascii_le tters+string.di gits
        >>> n=3
        >>> [s[i:i+n] for i in range(0,len(s), n)]
        ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yzA', 'BCD', 'EFG', 'HIJ', 'KLM', 'NOP', 'QRS', 'TUV', 'WXY', 'Z01', '234', '567', '89']
        >>> [/code]

        Comment

        • Eyes Of Madness
          New Member
          • Mar 2008
          • 5

          #5
          thanks guys that all helped a lot. The help was much appreciated.

          Comment

          Working...