1

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
Korozin
  • 13
  • 2

6 Answers6

1

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:

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 1
    Just to note, that's an overly complex example. Usually you don't put the string in the string, and they were asking about using a variable `TestVar`. – Peter Wood May 18 '22 at 21:15
  • @PeterWood, sure - the point was to create an example that could be immediately pasted into Python and run without defining any other variables. I was actually aiming for a very simple example, but apparently ended up with a complex one:P – ForceBru May 18 '22 at 21:21
  • @ForceBru It was actually quite easy to understand, and it allows for conversion to hex much faster as opposed to the conversion table variable I had written. – Korozin May 18 '22 at 21:59
0

The .zfill string method can be used.

For example:

s = 'C30'
s.zfill(8)

>>> '00000C30'
S3DEV
  • 8,768
  • 3
  • 31
  • 42
0

Try this code

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

0

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

0

Use string function rjust():

print(test.rjust(8,'0'))
Alo
  • 16
  • 2
0

try something like this str.rjust() function

i = 1111
pad = '0'
n = 8

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