2013-08-27 34 views
0

我有一個包含時間和活動字符串的元組。因此,這將是與此類似:在換行符上分割python中的字符串

('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中做到這一點?謝謝。

回答

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

偉大的答案。如果你想將每一行分成時間和活動,你可以使用'line.split(None,1)'或'line.partition('')'。 – abarnert

+0

@abarnert:實際上分割爲'':'';現在我的輸出與問題示例相匹配。 –

+0

非常詳細和現場答案。謝謝,並感謝其他回覆。 – avaholic

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 
0

你似乎沒有一個元組,你有一個字符串,如果你打印,它會給你準確的東西。

假設你有一個元組列表(我以爲是你的意思),你應該做這樣的事情:

input = [("8:01", "Woke Up"), ("8:05", "Took shower"), ("8:20", "Ate Breakfast")] 
for time, description in input: 
    print time, description 
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]