MITHU
MITHU

Reputation: 154

Unable to get fractional portion of some tuples

I've a text file which contains different information in different lines within tuple. I wish to get the fractional portion within ' ' of each tuple.

The data in the text file look like:

('Corredor Sanchez', 'Clara', '663354212','[email protected]')
('Berea Castejon', 'Jorge', '934518811',''[email protected]'')
('Juarez Cruz', 'Veronica', '',''[email protected]'')

Expected output I wish to get:

Corredor Sanchez, Clara, 663354212, [email protected]
and so on -----

I've tried with:

with open("data.txt","r") as f:
    for item in f.readlines():
        container = item.strip()
        last_name = container[0]
        print(last_name)
        break

I'm getting ( when I run the script above.

How can I modify the script to get the output I've shown above?

Upvotes: 0

Views: 35

Answers (1)

user120242
user120242

Reputation: 15268

You can use ast.literal_eval to parse a (valid Python) literal in string form:

import ast

with open("data.txt","r") as f:
    for item in f.readlines():
        container = ast.literal_eval(item.strip())
        last_name = container[0]
        print(last_name)
        break

Upvotes: 2

Related Questions