如果你不想要一個正則表達式,你可以這樣做: 這是假設你有很多行的輸入,並把它們全部放在列表的列表中。 它返回一個列表,其中每個元素都是正確解析的字符串。
這只是假定您的字段被一個空格分隔,並且您希望在前兩個字段之間沒有管道。
# 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)))
非常感謝。這正是我需要的。 – 2011-04-23 14:25:56