Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading