How to format Python code to always return this specific length

Sorry if this is a bit of a noob question. But moving on..

Say at the beginning of my code I set a variable, like this:

TestVar = 'A6'

But I later want it to print out as 000000A6

Or say it was

TestVar = 'C30'

I’d want it to print out as 00000C30

Basically always returning it with a length of 8

The reasoning for this is I’ve made a general script for modding a game, (I can link if asked) and you need to put in certain values which I want to have format automatically for ease of use. For example on running it’ll print

Item ID Here: 

And if you put in 166 it would convert the decimal number to hex which would be A6, however in order to be usable for all values (not just ones that are 2 digits once converted) I’m trying to make it detect it’s length and format it with the 0s before.

Sorry if this doesnt make sense, in a simpler way of saying this, is there a way for it to detect the length of a variable? So for example in pseudo

TestVar = 'C30'

    If TestVar length = 3
         print('00000'+TestVar)

Print Result: 00000C30

>Solution :

Use string function rjust():

print(test.rjust(8,'0'))

Leave a Reply