Gus
Gus

Reputation: 43

Python: Ignoring a single space when data is separated by two spaces

Very new to Python here. I have this text file, where it shows whether those people work on Fall, Winter, Spring, Summer respectively (marked by x).

For example, Mary works on Fall, Winter, and Spring, but not on Summer. John works all seasons.

Mary  x  x  x 
John  x  x  x  x 
Anne        x 
Drew

Each of the fields is separated by two spaces, followed by a \n on the end. So what I did was

with open("testfile.txt") as inputFile :
    aline = inputFile.readline()
    while aline != "" :
        field = aline.rstrip().strip().split("  ")
        .....

My problem now is that for Anne, for every empty spot for the 'x', the .split(" ") will split that empty spot. Therefore Anne is considered to work on Summer, instead of Spring because those spots for 'x' are considered part of the splitting.

How can I somehow 'ignore' those spaces and have Anne work for Spring?

Upvotes: 0

Views: 76

Answers (1)

DYZ
DYZ

Reputation: 57033

Replace every three consecutive spaces with two spaces and some other symbol and them apply the split:

aline = aline.replace("   ", "  -")
# 'Anne  -  -  x '
aline.strip().split("  ") # strip() for removing the trailing white space
# ['Anne', '-', '-', 'x']

Upvotes: 2

Related Questions