0

If I do something like this:

print "%08d" % 2

It will print '00000002'. However, I want to change the "8" to a "3" at runtime (to get '002' instead). I tried this:

MyLength = 3
print "%0" + str(MyLength) + "d" % 2

but I get: "TypeError: not all arguments converted during string formatting"

Can anyone see what's wrong with that?

Thanks,
Dave

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by daviddoria
1

I think you'll probably need to make use of eval in this case:

>>> myLengths = [3, 8, 5]
>>> for eachLength in myLengths:
...     print eval("'%0" + str(eachLength) + "d' % 2")
...     
002
00000002
00002
>>>

Unless you're willing to split your above code into two steps like this:

>>> my_str = "%0" + str(myLength) + "d"
>>> my_str % 2
'002'
>>>

What's happening now is it's trying to evaluate "d" % 2 . You need to make sure the string formatting and concatenation happens before trying to use the "outer" format. If that makes sense

Votes + Comments
Perfect, quick answer!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.