DarthOpto DarthOpto - 2 months ago 6
Python Question

'long' object has no attribute '__getitem__' Error

I am writing a function to help out our test department put random phone numbers into a phone number field.

Here is my code:

from random import randrange

def phonenumbergenerator():
phonenumber = randrange(1111111111, 9999999999)
phonenumberformatted = (str("%s-%s-%s" % (phonenumber[:3], phonenumber[3:6], phonenumber[6:])))
return phonenumberformatted

print phonenumbergenerator()


I am getting the following error when I try to run this and I am not sure what I am doing incorrectly here:

TypeError: 'long' object has no attribute '__getitem__'

Answer

The problem is phonenumber is an int, not yet a str. __getitem__ is the [:3] notation. Easiest solution:

from random import randrange

def phonenumbergenerator():
    phonenumber = str(randrange(1111111111, 9999999999)) # <-- make it a string
    phonenumberformatted = (str("%s-%s-%s" % (phonenumber[:3], phonenumber[3:6], phonenumber[6:])))
    return phonenumberformatted

Gave me:

>>> phonenumbergenerator()
415-867-5309

A good way to troubleshoot exceptions like this is to split the work onto multiple lines, so you have a better idea of where the exception occurred. For instance:

area_code = phonenumber[:3]
prefix    = phonenumber[3:6]
suffix    = phonenumber[6:]
phonenumberformatted = (str("%s-%s-%s" % (area_code, prefix, suffix)))