Dev012
Dev012

Reputation: 273

Extracting numbers from a string in Python

When I query my MySQL Database I get some extra characters that I don't want. For example, instead of getting 165 I get (165), so, I tried the following in order to extract the number.

The problem is that instead of getting only the number, my code will print nothing, I can't find the reason. Any advice?

 arr = ''

    num = re.findall('\d+', arr)

    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        database="diff"
    )

    mycursor = mydb.cursor()

    mycursor.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
    myresult = mycursor.fetchall()

    for x in myresult:
        arr = x        
        print(arr)

Upvotes: 0

Views: 69

Answers (3)

Sam Mason
Sam Mason

Reputation: 16184

most Python database connectors I've used give back tuples, you'd thus want to do:

for (x,) in myresult:
  print(x)

and you should get what you want

the docs I get suggest you can also just the cursor an iterable context manager, thus something like:

with mydb.cursor() as cur:
  cur.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
  for (x,) in cur:
    print(x)

would be more idiomatic Python

Upvotes: 1

ramin
ramin

Reputation: 968

something like this maybe:

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="Bellini10-",
    database="diff"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
myresult = mycursor.fetchall()

pattern = re.compile("\d+") 

for x in myresult:
    num = pattern.findAll(x)[0]       
    print(num)

Upvotes: 2

Om A.
Om A.

Reputation: 140

Try this:

whitelist = set('0123456789')
num = ''.join(filter(whitelist.__contains__, arr))

Hope this helps!

Upvotes: 1

Related Questions