在换行符上拆分python中的字符串

split a string in python on linebreaks

本问题已经有最佳答案,请猛点这里访问。

我有一个包含一连串时间和活动的元组。因此,它类似于:

1
2
3
4
('08:01: Woke Up
08:05: Took Shower
08:20: Ate Breakfast
08:45: Left for work'
, )

我需要能够接受每一项活动并像这样单独显示:

1
2
3
4
8:01 Woke Up
8:05 Took Shower
8:20 Ate Breakfast
8:45 Left for work

有人能给我一个关于用Python实现这一点的最佳/最简单方法的建议吗?谢谢您。


元素中已经有换行符,所以只需打印:

1
2
3
4
5
6
7
8
9
>>> tup = ('08:01: Woke Up
08:05: Took Shower
08:20: Ate Breakfast
08:45: Left for work'
,)
>>> print tup[0]
08:01: Woke Up
08:05: Took Shower
08:20: Ate Breakfast
08:45: Left for work

可以使用str.splitlines()将字符串拆分为单独的元素:

1
2
3
4
5
6
7
8
9
>>> tup[0].splitlines()
['08:01: Woke Up', '08:05: Took Shower', '08:20: Ate Breakfast', '08:45: Left for work']
>>> for line in tup[0].splitlines():
...     print line
...
08:01: Woke Up
08:05: Took Shower
08:20: Ate Breakfast
08:45: Left for work

如果需要将时间和活动作为单独的字符串,请将字符串': '上的每一行拆分为:

1
2
3
4
5
6
7
8
>>> for line in tup[0].splitlines():
...     time, activity = line.split(': ', 1)
...     print time, activity
...
08:01 Woke Up
08:05 Took Shower
08:20 Ate Breakfast
08:45 Left for work


你想过字典吗?您可以将时间信息存储为键,将活动存储为值,例如:

1
2
3
4
5
dictionary = {}
dictionary['8:01'] = 'Woke Up'
dictionary['8:05'] = 'Took Shower'
dictionary['8:20'] = 'Ate Breakfast'
dictionary['8:45'] = 'Left for work'

然后以您可以简单地执行的格式打印:

1
2
for k in dictionary:
    print k + ' ' + dictionary[k]


你似乎没有一个元组,你有一个字符串,如果你打印,它会给你准确的你想要的。

假设你有一个元组列表(我想这就是你的意思),你应该这样做:

1
2
3
input = [("8:01","Woke Up"), ("8:05","Took shower"), ("8:20","Ate Breakfast")]
for time, description in input:
  print time, description

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> t = ('08:01: Woke Up
08:05: Took Shower
08:20: Ate Breakfast
08:45: Left for work'
, )
>>> for elem in t:
...     print elem.split('
'
)
...
['08:01: Woke Up', '08:05: Took Shower', '08:20: Ate Breakfast', '08:45: Left fo
r work'
]
>>> for elem in t:
...     for activity in elem.split('
'
):
...             print activity
...
08:01: Woke Up
08:05: Took Shower
08:20: Ate Breakfast
08:45: Left for work
>>> for elem in t:
...     print elem
...
08:01: Woke Up
08:05: Took Shower
08:20: Ate Breakfast
08:45: Left for work