0

Possible Duplicate:
Python: Split string with multiple delimiters

I have a program where I am parsing a file by each line and splitting it into two half. After that for each half I am parsing each word from the line and appending it in a list.

Here mfcList1 is a list of lines from a text file. I am parsing each word in the line that are either separated by a comma or by a space. But it isn't exactly working.

for lines in mfcList1:
        lines = lines.lstrip()
        if lines!='':
            p.append(string.split(lines,','or " "))
mfcList2 = reduce(lambda x,y:x+y,p)

print mfcList2

When i am using string.split it is working with only those elements who end with a comma it is ignoring the or operator I am using with split method. I want to slice off each and everyword from the line. They either end with a comma or with a space.

for eg. 'enableEmergencySpare=1 useGlobalSparesForEmergency=1 useUnconfGoodForEmergency=1',

this line is being stored as a single list element where as I am trying to split them using split method..

Can anyone pls suggest what i can do instead of using or operator... thanks..

Community
  • 1
  • 1
rain
  • 363
  • 6
  • 15

1 Answers1

1

You can use split() from the re module:

import re
...
p.extend(re.split('[ ,]', lines))

The [ ,] is a regular expression which means "a space or a comma". Also, assuming p is a list and you want to add all the words to it, you should use extend() rather than append(), the latter adds a single element.

Note also that if a line in the file contains command followed by space (or other sequence of commas and spaces) your list p will contain a corresponding number of empty strings.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
  • it didn't display the output in the list format. I want the output as a list..it just showed output as words separated by spaces but not a as a list. – rain Jan 12 '12 at 20:01
  • Well, yes, because you combine all the elements of the list with `reduce()`. If you don't want to do it, then don't call `reduce()` and instead just display the list populated in the loop (i.e. `p`). – Adam Zalcman Jan 12 '12 at 20:12
  • it is still printing the same thing. it is taking only , enableEmergencySpare=1 useGlobalSparesForEmergency=1 useUnconfGoodForEmergency=1 – rain Jan 12 '12 at 20:31
  • i think i got it now.. thanks for the solution – rain Jan 12 '12 at 20:33