在python中将数组中的字符串存储在Array中

时间:2013-05-08 08:33:25

标签: python

我的字符串包含这样的大段:

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 "

我想将ID之上的信息存储到这样的数组中:

 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

数组应该继续,因为我在字符串中有更多的数据,这个数据很大,数组应该自动组成,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

编辑:使用你的字符串。

注意:这可能是一种更简洁的方法。

您可以使用正则表达式:

>>> 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