2011-04-23 44 views

回答

3

使用正則表達式替換:

import re 

text = 'hello world 2,000 3,000' 
print re.sub(r'\s(\d)', '|\\1', text) 

這只是插入的東西用一個空格和一個數字之前的管道標誌。

+0

非常感謝。這正是我需要的。 – 2011-04-23 14:25:56

1

如果你不想要一個正則表達式,你可以這樣做: 這是假設你有很多行的輸入,並把它們全部放在列表的列表中。 它返回一個列表,其中每個元素都是正確解析的字符串。

這只是假定您的字段被一個空格分隔,並且您希望在前兩個字段之間沒有管道。

# one line of input 
text = 'hellow world 1,000 2,000' 
testlist = text.split(' ') 

# all your input 
list_of_all_text = [testlist] + [testlist] + [testlist] 

first_feilds = map(lambda x: x[0]+' '+x[1],list_of_all_text) 
last_feilds = map(lambda x: x[2:],list_of_all_text) 
all_feilds = map(lambda x,y: [x]+y,first_feilds,last_feilds) 
parsed_feilds = map(lambda x: '|'.join(x),all_feilds) 
print parsed_feilds 

或更少可讀和更緊湊:

text = 'hellow world 1,000 2,000' 
testlist = text.split(' ') 
list_of_all_text = [testlist] + [testlist] + [testlist] 
map(lambda x: '|'.join(x),map(lambda x,y: [x]+y,map(lambda x: x[0]+' '+x[1],list_of_all_text),map(lambda x: x[2:],list_of_all_text))) 
2

你必須由空格隔開的三個字段和所述第一場還可以包含空格。您可以使用帶有maxsplit參數的rsplit將字符串分成三部分。

text = 'hello world 2,000 3,000' 

# Split at the two rightmost spaces, so that 
# the leftmost of the three fields can contain spaces 
parts = text.rsplit(' ', 2) # ['hello world', '2,000', '3,000'] 

result = '|'.join(parts) # 'hello world|2,000|3,000' 
相關問題