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

Recommended Answers

All 2 Replies

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

commented: Perfect, quick answer! +3

Perfect - thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.