Reputation: 99
I read a text file in python as:
anagram = []
with open('test.txt', 'r') as text_file:
for lines in text_file:
anagram.append(lines.strip().split(','))
print (anagram)
where it prints:
[['pot', 'top'], ['room', ' door'], ['wink', ' true']]
when I ask for the type it says class list. So I run the following code to convert it into string:
alist = str(anagram[0])
however, when I run the following code:
print (alist[0])
I get the following result:
[
instead, I want to get the word pot.
How can I do that?
Upvotes: 1
Views: 42
Reputation: 1565
If we run these lines in a terminal:
>>> anagram = [['pot', 'top'], ['room', ' door'], ['wink', ' true']]
>>> alist = str(anagram[0])
>>> alist
"['pot', 'top']"
>>> alist[0]
'['
You can see that the line alist = str(anagram[0])
is converting the first list
in anagram
into a string
. Then alist[0]
is getting the first character from that string: [
.
Just remove the str
and you will get the list:
alist = anagram[0]
Upvotes: 1
Reputation: 366
Remove the string casting altogether. It turns the list to it's string representation, "['pot', 'top']". It's first character is indeed '['.
This will print what you're looking for:
alist = anagram[0]
print(alist[0])
Upvotes: 2