0

I am not sure why I am getting an extra comma at the end of every output when using the Match() with Regex in python. Any ideas ? Thanks.

My Code:

 import re

 yyyyfile = open("yyyy.txt",'w')

 text = open('final.txt')

 for line in text: 

    x = re.match('.*?^([0-9][0-9][0-9][0-9])$.*', line)

    if x:

        print >> yyyyfile, x.groups()

Current Output:

('1573',)

('1595',)

('1929',)

('1933',)

Desired Output:

('1573')

('1595')

('1929')

('1933')

3
  • Can you show some examples of what the lines from the files look like? (from final.txt) Commented Nov 22, 2017 at 14:29
  • Nothing wrong with a tuple, is it? Commented Nov 22, 2017 at 14:32
  • What is your regex supposed to do ? It feels like '[0-9]{4}' should do the trick ? Commented Nov 22, 2017 at 14:37

3 Answers 3

4

It's because the output of re.match's groups() is all of the groups that you captured. It's a tuple.
Use x.group(1) or whatever instead.

Sign up to request clarification or add additional context in comments.

Comments

0

You are not getting an extra comma because you using match. The reason you get this comma is that you are printing out tuples. You can achieve the desired result like this

print >> yyyyfile, '(%s)' % x.group(1)

Comments

0

I don't know what is inside yyyy.txt and why you want to print it but assuming final.txt includes the text you should open the file with:

with open('final.txt', 'r') as f:
    text = f.read()

parsing works like this:

import re

text = '''1235, dfx as nxcn 1229 nxcn 32 4 0 9877'''

matches = re.findall('(\d{4})', text)

for match in matches:
    print(match)

2 Comments

Thanks for reaching out. I received the following error after running the code you provided. TypeError: 'NoneType' object is not iterable
I updated my answer to provide a verifiable example. Also I simplified the regex.

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.