Reputation: 1395
I know that regex is the way to go here but I am woeful at writing regex expressions. I have a file where each line looks like this: "defenders\t2\n" and I want to remove the \t and the \n and put the word "defenders" into the [0] of my multidimensional list and put the number "2" in the [1] of my list. Is there an easy regex way to do this in python?
import re
d = []
with open("somefile.txt") as f:
for line in f:
word = re.search()
rank = re.search()
d.append([word][rank])
This is what I am trying but I do not know how to make it work. Thanks for the help.
Upvotes: 2
Views: 105
Reputation: 250961
Just use str.split
:
>>> "defenders\t2\n".split()
['defenders', '2']
To get a list using regex, you need to use re.findall
:
>>> import re
>>> re.findall(r'\S+', "defenders\t2\n")
['defenders', '2']
Upvotes: 1