2

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.

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

1 Comment

And if he wants line[1] to be an int instead of a string, just do line[1] = int(line[1])

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.