0

I'm trying to print the last digit of an integer that's been pulled from a database and converted to a string. normally, this code works fine to print the last character of a string even if its a number thats been coverted to a string:

x = 225
print x[-1]
5

However, when I try to do the same thing on a value thats been pulled from a database, the Python interpreter gives me a string index out of range error.

Here is my code:

import MySQLdb

#mysql card_numbercheck
class NumberCheck(object):
    def __init__(self):
        self.conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='mscan')
        self.c = self.conn.cursor()

    def query(self, arg, cardname):
        self.c.execute(arg, cardname)
        return self.c

    def __del__(self):
        self.conn.close()

# Define SQL statement to select all Data from Column Name
sql = "SELECT card_number FROM inventory_2 WHERE card_name = %s"

#Connect To DB and Get Number of Card. 
def Get_MTG_Number():
    global card_number
    MtgNumber = NumberCheck()
    for number in MtgNumber.query(sql, 'Anathemancer'):
        card_number = str(number[0])

    print card_number[-1]        

Get_MTG_Number()

Logically, I don't really understand why this code wouldn't work. Any help would be highly appreciated.

Kind Regards Jack

1 Answer 1

0

Maybe some of the data fields are blank, and by converting to a string you are just getting an empty string? Trying to index such a string will give you an 'index out of range' error.

To see what is going on, you could simply print card_number upon each iteration of the loop. You could also do with a bit more error handling to sanitize the data you are getting from a database.

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

Comments

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.