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

时间:2013-08-27 21:06:14

标签: python split

我有一个包含一系列时间和活动的元组。所以,它将类似于:

('08:01: Woke Up\n08:05: Took Shower\n08:20: Ate Breakfast\n08:45: Left for work', )

我需要能够像以下一样单独进行每项活动和展示:

8:01 Woke Up
8:05 Took Shower
8:20 Ate Breakfast
8:45 Left for work

有人能给我一个关于在python中做到这一点的最佳/最简单方法的建议吗?谢谢。

4 个答案:

答案 0 :(得分:9)

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

>>> tup = ('08:01: Woke Up\n08:05: Took Shower\n08:20: Ate Breakfast\n08: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()

将字符串拆分为单独的元素
>>> 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

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

>>> 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 :(得分:0)

>>> t = ('08:01: Woke Up\n08:05: Took Shower\n08:20: Ate Breakfast\n08:45: Left for work', )
>>> for elem in t:
...     print elem.split('\n')
...
['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('\n'):
...             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

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

你有没有想过字典?您可以将时间信息存储为键,将活动存储为值,如下所示:

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

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

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