Split() [solved with re.split]

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • MaxLindquist
    New Member
    • Oct 2006
    • 24

    #1

    Split() [solved with re.split]

    How do make a split on a string at a few different places? For example i wanna make a split on 5*4+1-1+3 to put all the numbers in a list. How do i do that?
  • Geos
    New Member
    • Oct 2006
    • 2

    #2
    Hi,

    This should do the job although I don't believe it is the best solution.


    a = "1+2-3+5-6*8"
    z = []
    for x in a:
    try :
    int(x)
    z.append(x)
    except:
    pass
    print z

    greetz Geos

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by Geos
      Hi,

      This should do the job although I don't believe it is the best solution.


      a = "1+2-3+5-6*8"
      z = []
      for x in a:
      try :
      int(x)
      z.append(x)
      except:
      pass
      print z

      greetz Geos
      Geos, Please use code tags so your post looks like this:
      Code:
      a = "1+2-3+5-6*8"
      z = []
      for x in a:
      	try :
      		int(x)
      	z.append(x)
      	except:
      		pass
      print z
      Otherwise, it is very hard to use. Thanks,
      Barton

      Comment

      • fuffens
        New Member
        • Oct 2006
        • 38

        #4
        You can use a regular expression to split the string. You still have to go through the list to convert to integers as in the previous example though.

        Code:
        import re
        re.split('[*+-]', '5*4+1-1+3')
        Best regards
        /Fredrik

        Comment

        • bartonc
          Recognized Expert Expert
          • Sep 2006
          • 6478

          #5
          Originally posted by fuffens
          You can use a regular expression to split the string. You still have to go through the list to convert to integers as in the previous example though.

          Code:
          import re
          re.split('[*+-]', '5*4+1-1+3')
          Best regards
          /Fredrik
          This is VERY cool! I've used the re module, but hadn't come across this usage. Thanks Fredrik!
          Barton

          Comment

          • kudos
            Recognized Expert New Member
            • Jul 2006
            • 127

            #6
            Here is a possible solution...

            Code:
            for a in "5*4+1-1+3".split("*"):
             for b in a.split("+"):
              for c in b.split("-"):
               print c
            -kudos


            Originally posted by MaxLindquist
            How do make a split on a string at a few different places? For example i wanna make a split on 5*4+1-1+3 to put all the numbers in a list. How do i do that?

            Comment

            Working...