1

For example: content of myfile has

    fsdfasf
    frjfmcd
    39djaxs

I want to convert this in to a matrix where it consists of my_matrix=[['f','s','d','f','a','s','f'],['f','r','j'......]]

I've tried reading the file using

for line in file:
        line = line.strip('\n)
        print(line)

But it's not giving me the desired output.

What am I missing to do?

1
  • Convert each line to a list (list(line) should do) and append each list to a final result list. Commented Nov 14, 2020 at 21:30

1 Answer 1

4

You need to turn your string into a list to get the output you want. Since strings are sequences, when you pass a string to list() if breaks it up into individual characters:

with open(path) as file:
    matrix = [list(line.strip()) for line in file]
    

matrix:

[['f', 's', 'd', 'f', 'a', 's', 'f'],
 ['f', 'r', 'j', 'f', 'm', 'c', 'd'],
 ['3', '9', 'd', 'j', 'a', 'x', 's']]
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, this resolved my problem. I am not familiar with the notation you used for variable matrix. What is it called and how can I convert it into a notation that is "easier"
@RaeLeng that's called a list comprehension — it's not to hard once you get used to it and it's pretty fundamental to python.

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.