0

My string contains large paragraph like this:

Line= "

      Name       =    AB    | 1-2 |      Name
      ID         =    CD    | 3-4 |      int
      Stu        =    EF    | 5-6 |      Name
      Email      =    GH    | 7-8 |      string
      ID         =    IJ    | 9-10 |     int
      Tea        =    KL    | 1--12 |    Name
      Email      =    MN    | 13-14 |    Name
      ID         =    OP    | 1-2 |      int "

I want to store information which come above ID into an array like this:

 A[0] = Name       =    AB    | 1-2 |      Name
 A[1] = Stu        =    EF    | 5-6 |      Name
        Email      =    GH    | 7-8 |      string
 A[2] = Tea        =    KL    | 1--12 |    Name
        Email      =    MN    | 13-14 |    Name

The array should continue as I have more data in string which is large, the array should be made up automatically, Can someone help?

1
  • 1
    I'm pretty sure, you're choice should be a dict. Commented May 8, 2013 at 8:37

1 Answer 1

2

EDIT: Used your string.

Note: There's probably a cleaner way to do this.

You can use regex:

>>> import re
>>> Line = """

  Name       =    AB    | 1-2 |      Name
  ID         =    CD    | 3-4 |      int
  Stu        =    EF    | 5-6 |      Name
  Email      =    GH    | 7-8 |      string
  ID         =    IJ    | 9-10 |     int
  Tea        =    KL    | 1--12 |    Name
  Email      =    MN    | 13-14 |    Name
  ID         =    OP    | 1-2 |      int """
>>> Line = '\n'.join(i.lstrip() for i in Line.strip().splitlines())
>>> newlist = [i.strip('\n') for i in re.split(r'ID.*',Line)]
>>> print newlist[0]
Name       =    AB    | 1-2 |      Name
>>> print newlist[1]
Stu        =    EF    | 5-6 |      Name
Email      =    GH    | 7-8 |      string
>>> print newlist[2]
Tea        =    KL    | 1--12 |    Name
Email      =    MN    | 13-14 |    Name
Sign up to request clarification or add additional context in comments.

7 Comments

Error when print newlist[1]: list index out of range
@hulk007 You must be doing something wrong, as this is also happening to you on jamylak's answer. Did you copy my code exactly?
print newlist[0] is giving me the whole string without change
What I don't understand is why you have taken Line = """\, i dont have this, I have line="
@hulk007 What do you have? The code given in the question is not a valid multiline string
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.