'How to format Python code to always return this specific length [duplicate]

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 1:[1]

Use string function rjust():

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

Solution 2:[2]

Basically always returning it with a length of 8

That's what format strings do:

>>> print(f"{'C30':>08s}")
00000C30

As a sidenote, to output any number as 8-digit hex:

>>> print(f"{100:>08X}")
00000064
>>> print(f"{1024:>08X}")
00000400

See the documentation:

Solution 3:[3]

The .zfill string method can be used.

For example:

s = 'C30'
s.zfill(8)

>>> '00000C30'

Solution 4:[4]

Try this code

txt = "A6"
x = txt.zfill(8)
print(x)

Solution 5:[5]

You can use string.zfill method

for example.

code = '3C0'
filledCode = code.zfill(8)

this method filled with zero the number of digit that you pass like a parameter

Solution 6:[6]

try something like this str.rjust() function

i = 1111
pad = '0'
n = 8

x = str(i).rjust(n, pad)
print(x)    # 00001111

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alo
Solution 2 ForceBru
Solution 3 S3DEV
Solution 4 Daniel Lima
Solution 5
Solution 6 rich