0

I have a text file called animal.txt.

1.1  Animal Name  : Dog
     Animal Type  : Mammal
     Fur          : Yes
     Scale        : No

1.2  Animal Name  : Snake
     Animal Type  : Reptile
     Fur          : No
     Scale        : Yes

1.3  Animal Name  : Frog
     Animal Type  : Amphibian
     Fur          : No
     Scale        : No

1.x  Animal Name  : aaaaaa
     Animal Type  : bbbbbb
     Fur          : cccccc
     Scale        : dddddd

My desired ouput is:

Dog     Mammal      Yes
Snake   Reptile     No
Frog    Amphibian   No

Output I am getting is:

Dog Mammal Yes
Snake Reptile No
Frog Amphibian No 

This is the code I currently have that prints out my current input.

with open('animal.txt', 'r') as fp:
for line in fp:
    header = line.split(':')[0]
    if 'Animal Name' in header:
        animal_name = line.split(':')[1].strip()
        print animal_name,
    elif 'Animal Type' in header:
        animal_type = line.split(':')[1].strip()
        print animal_type,
    elif 'Fur' in header:
        fur = line.split(':')[1].strip()
        print fur
    elif '1.x' in header:
        break

Is there a way to format or add to my existing code that will give me my desired output?

6406119
  • 17
  • 1

1 Answers1

-1

Use \t between the items you are printing. So print animal_name\t, then so on through the rest of your code.

with open('animal.txt', 'r') as fp: for line in fp: header = line.split(':')[0] if 'Animal Name' in header: animal_name = line.split(':')[1].strip() print animal_name\t, elif 'Animal Type' in header: animal_type = line.split(':')[1].strip() print animal_type\t, elif 'Fur' in header: fur = line.split(':')[1].strip() print fur\t elif '1.x' in header: break

Colby
  • 106
  • 8