1

I'm relatively new to python (experience in c#), and I have a list in a text file that I dumped into a list using;

with open(fname) as f:
    content = f.readlines()
content = [x.strip() for x in content] 

The thing is, every line is in the form XXXXX, XXXXX (with varying lengths of XXXXX), and I want to convert f into a 2-dimensional array with things in the line before the comma in the first dimension and everything after in the second.

What's the best practice for doing something like that?

1 Answer 1

2

Just use .split(','):

From the documentation, we can see that the string method .split will:

Return a list of the words in the string, using sep as the delimiter string.

So to give an example, taking the string:

s = "abcd, efgh"

then we can do:

s.split(', ')

to get a list:

['abcd', 'efgh']

So for your application, just throw it in the list-comprehension:

with open(fname) as f:
    content = f.readlines()
content = [x.strip().split(', ') for x in content] 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.