MindlessMaik
MindlessMaik

Reputation: 291

get first digit in a string in python

this is my first day with python and i'm stuck. I have a file which content looks like this:

If the user choose foo, I just want to return 1,2, 4 and 23546477 and write in a file:

This is what I have come up so far:

import sys
import re

def merge():

   if (len(sys.argv) > 1):
    labfile = sys.argv[1]
    f = open(labfile, 'r')
    f.readline()
    string = f.readline()
    print "Possible Target States:"
    print string
    var = raw_input("Choose Target States: ")
    print "you entered ", var
    f.readline()
    words = var.split()
    for line in f.readlines():
      for word in words:
        if word in line:
          m = re.match("\d+", line)
          print m
          //get the first number and store it in a list or an array or something else

    f.close()

merge() 

unfortunately it is not working - I see lines like <_sre.SRE_Match object at 0x7fce496c0100> instead of the output I want.

Upvotes: 0

Views: 1852

Answers (2)

dimo414
dimo414

Reputation: 48804

Look at the documentation - re.match returns a Match object, which is what you're seeing. re.findall will give you a list of strings matching a pattern in a given line.

To get just the first, you do want to use Match objects, but you want re.search not re.match and then you need to call m.group() to get the matched string out of the Match object.

Upvotes: 0

mgilson
mgilson

Reputation: 309889

You want to do (at least):

if m:  #only execute this if a match was found
   print m.group()  #m.group() is the portion of the string that matches your regex.

Upvotes: 1

Related Questions