Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trouble obtaining elements of string split from list

I am reading a document as follows:

Title of document
[[subtitle of document]] 
etc 

I am opening it with doc = open(path, ‘r’).read(), and I want to be able to just select the first and second lines.

When I use doc.split("\n") it returns a list [‘Title of document’, ‘subtitle of document’, ‘etc’] as expected. Also as expected doc.split("\n")[0] returns ‘Title of document’, but for some reason doc.split("\n")[1] returns "list index out of range". How could this be, when it shows element 1 as being there in the list?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You get the "list index out of range" because you are splitting a string.
do a print(type(doc)) and you’ll see.

The result of doc.split('\n') will be the list you want. After that, you can extract the values by indexing them.

doc = open('example.txt', 'r').read()
print(type(doc))

doc_list = doc.split('\n')
print(type(doc_list))
print(f'first: {doc_list[0]}')
print(f'second: {doc_list[1]}')

Then the result

<class 'str'>
<class 'list'>
first: Title of document
second: [[subtitle of document]] 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading