2012-06-26 61 views
1

我有一個文件,我輸出幾列信息,確切地說是4。在這一刻,它們之間用逗號隔開,但爲了讓我的好友把它們送入另一個腳本,他希望格式與'|'作爲分隔符,並刪除了逗號,逗號跟隨每一組數據,所以我的腳本後,它輸出這樣的:添加delimeters並刪除逗號

[0], [1], [2], [3] 

我需要的是:

[0] | [1] | [2] | [3] 
+0

你有什麼企圖自己做呢?如果是這樣,請顯示代碼。 – martineau

回答

3
s = "[0], [1], [2], [3]" 

print s.replace(',', ' |') 

# Output: 
# [0] | [1] | [2] | [3] 

會爲你的工作測試用例。

或者,你可以得到瘋狂的東西,如

s = "[0], [1], [2], [3]" 

s = s.split(',') 
s = map(str.strip, s) 
s = " | ".join(s) 

print s 
# Output: 
# [0] | [1] | [2] | [3] 

根據您的需要可能會更靈活。

2
>>> print ' | '.join('[0], [1], [2], [3]'.split(', ')) 
[0] | [1] | [2] | [3] 

UPDATE:

其實@使用replace jedwards的解決方案是更好的:

>>> timeit.timeit("'[0], [1], [2], [3]'.replace(', ', ' | ')") 
0.36054086685180664 

>>> timeit.timeit("' | '.join('[0], [1], [2], [3]'.split(', '))") 
0.48539113998413086