在编号中拆分字符串

时间:2013-10-02 08:28:17

标签: python python-3.x

假设我希望我的文本文件包含一系列命令:

1. eat, food
   7am
2. brush, teeth
   8am
3. crack, eggs
   1pm

我们怎样才能得到:

"eat, food\n7am"
"brush, teeth\n8am"
"crack, eggs\n1pm"

我正在尝试使用经典的split()循环,但到目前为止我还没弄清楚如何摆脱数字..有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用regexstr.splitlines

>>> import re
>>> s = """1. eat, food
   7am
2. brush, teeth
   8am
3. crack, eggs
   1pm"""
>>> lis = [re.sub(r'^\d+\.\s*', '', x).strip() for x in s.splitlines()]
>>> it = iter(lis)
>>> for x in it:
    print '{!r}'.format(x + '\n' + next(it))


'eat, food\n7am'
'brush, teeth\n8am'
'crack, eggs\n1pm'