My First Python Script

John Hazen john at hazen.net
Fri Sep 16 16:29:14 EDT 2005


* Ed Hotchkiss <edhotchkiss at gmail.com> [2005-09-15 20:36]:
> But then I still get the error with the len(x) statement .. hmm

Ahh.  In the future, it will help us help you, if you make it clear that
there was an error, and *paste the exact error* into your mail.

For example, I'm guessing the error you got is:

>>> len(255)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: len() of unsized object


As Robert said, this is because integers don't have a length.

James' suggestion to use string formatting is probably the "best"
solution, but the formatting codes are fairly daunting for someone never
exposed to them.

> if len(x) == 1:
>     mySet = '00' + str(x)
> elif len(x) == 2:
>     mySet = '0' + str(x)

You know intuitively that strings *do* have length, and you appear to
know how to create a string from an integer.  So the easiest
modification to your code to make it work wolud be something like:

mySet = str(x)
if len(mySet) == 1:
    mySet = '00' + mySet
elif len(mySet) == 2:
    mySet = '0' + mySet

Now, this can be made a little more elegant (and generalized) by using
the algorithm "if the string is too short, keep prepending zeros until
it's long enough."

target_length = 3
mySet = str(x)
while len(mySet) < target_length:
    mySet = '0' + mySet

But this isn't as efficient as your solution.  Once you know about the
interesting ability to multiply strings ("0" * 3 = "000"), you can
create a solution that's general, elegant, and efficient:

target_length = 3
mySet = str(x)
mySet = '0' * (target_length - len(mySet)) + mySet

HTH-

John



More information about the Python-list mailing list