Add leading zeros to a string without zfill, format, loops or control statementsBest way to format integer as string with leading zeros?Python string formatting: % vs. .formatHow can I print literal curly-brace characters in python string and also use .format on it?“Large data” work flows using pandasforloop in python pig latin translatorGlobal Variables between scriptsCheck statement for a loop only onceConvert float to string without scientific notation and false precisionAdd leading zeroes to a string PythonWeird strings that cause a newline but there is no control char

a sore throat vs a strep throat vs strep throat

How to limit Drive Letters Windows assigns to new removable USB drives

Checks user level and limit the data before saving it to mongoDB

"You've called the wrong number" or "You called the wrong number"

What is the optimal strategy for the Dictionary Game?

How could Tony Stark make this in Endgame?

Pulling the rope with one hand is as heavy as with two hands?

Is there a way to generate a list of distinct numbers such that no two subsets ever have an equal sum?

Is the claim "Employers won't employ people with no 'social media presence'" realistic?

How to denote matrix elements succinctly?

How would 10 generations of living underground change the human body?

Is Diceware more secure than a long passphrase?

Is there really no use for MD5 anymore?

Why does Mind Blank stop the Feeblemind spell?

Can someone publish a story that happened to you?

How come there are so many candidates for the 2020 Democratic party presidential nomination?

'It addicted me, with one taste.' Can 'addict' be used transitively?

"The cow" OR "a cow" OR "cows" in this context

How to fry ground beef so it is well-browned

Why didn't the Space Shuttle bounce back into space as many times as possible so as to lose a lot of kinetic energy up there?

Elements that can bond to themselves?

How to not starve gigantic beasts

Why did C use the -> operator instead of reusing the . operator?

Dynamic SOQL query relationship with field visibility for Users



Add leading zeros to a string without zfill, format, loops or control statements


Best way to format integer as string with leading zeros?Python string formatting: % vs. .formatHow can I print literal curly-brace characters in python string and also use .format on it?“Large data” work flows using pandasforloop in python pig latin translatorGlobal Variables between scriptsCheck statement for a loop only onceConvert float to string without scientific notation and false precisionAdd leading zeroes to a string PythonWeird strings that cause a newline but there is no control char






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have to add leading zeros to a string of variable length - to always fit a certain length. And I have to use very simple python without control structures such as if statements or while/forloops. It can be hard coded.



E.g.



 rannum = random.randrange(1, 999)
zero = "000"
rannumformat = (zero[0] + str(rannum))
print(rannumformat)


Do I need to use len() function as well?










share|improve this question



















  • 1





    Why can't you use zfill or format?

    – Artyer
    Mar 19 at 22:26






  • 1





    Do you want this string to be a specific length?

    – Andreas Lorenzen
    Mar 19 at 22:27






  • 1





    You do not need to use len to add a leading zero to a string.

    – wwii
    Mar 19 at 22:27






  • 1





    What is the expected output?

    – solarc
    Mar 19 at 22:29











  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. StackOverflow is not a coding, review, or tutorial resource.

    – Prune
    Mar 19 at 22:38

















0















I have to add leading zeros to a string of variable length - to always fit a certain length. And I have to use very simple python without control structures such as if statements or while/forloops. It can be hard coded.



E.g.



 rannum = random.randrange(1, 999)
zero = "000"
rannumformat = (zero[0] + str(rannum))
print(rannumformat)


Do I need to use len() function as well?










share|improve this question



















  • 1





    Why can't you use zfill or format?

    – Artyer
    Mar 19 at 22:26






  • 1





    Do you want this string to be a specific length?

    – Andreas Lorenzen
    Mar 19 at 22:27






  • 1





    You do not need to use len to add a leading zero to a string.

    – wwii
    Mar 19 at 22:27






  • 1





    What is the expected output?

    – solarc
    Mar 19 at 22:29











  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. StackOverflow is not a coding, review, or tutorial resource.

    – Prune
    Mar 19 at 22:38













0












0








0








I have to add leading zeros to a string of variable length - to always fit a certain length. And I have to use very simple python without control structures such as if statements or while/forloops. It can be hard coded.



E.g.



 rannum = random.randrange(1, 999)
zero = "000"
rannumformat = (zero[0] + str(rannum))
print(rannumformat)


Do I need to use len() function as well?










share|improve this question
















I have to add leading zeros to a string of variable length - to always fit a certain length. And I have to use very simple python without control structures such as if statements or while/forloops. It can be hard coded.



E.g.



 rannum = random.randrange(1, 999)
zero = "000"
rannumformat = (zero[0] + str(rannum))
print(rannumformat)


Do I need to use len() function as well?







python python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 13:46









Andreas Lorenzen

1,076412




1,076412










asked Mar 19 at 22:23









Bob SinghBob Singh

91




91







  • 1





    Why can't you use zfill or format?

    – Artyer
    Mar 19 at 22:26






  • 1





    Do you want this string to be a specific length?

    – Andreas Lorenzen
    Mar 19 at 22:27






  • 1





    You do not need to use len to add a leading zero to a string.

    – wwii
    Mar 19 at 22:27






  • 1





    What is the expected output?

    – solarc
    Mar 19 at 22:29











  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. StackOverflow is not a coding, review, or tutorial resource.

    – Prune
    Mar 19 at 22:38












  • 1





    Why can't you use zfill or format?

    – Artyer
    Mar 19 at 22:26






  • 1





    Do you want this string to be a specific length?

    – Andreas Lorenzen
    Mar 19 at 22:27






  • 1





    You do not need to use len to add a leading zero to a string.

    – wwii
    Mar 19 at 22:27






  • 1





    What is the expected output?

    – solarc
    Mar 19 at 22:29











  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. StackOverflow is not a coding, review, or tutorial resource.

    – Prune
    Mar 19 at 22:38







1




1





Why can't you use zfill or format?

– Artyer
Mar 19 at 22:26





Why can't you use zfill or format?

– Artyer
Mar 19 at 22:26




1




1





Do you want this string to be a specific length?

– Andreas Lorenzen
Mar 19 at 22:27





Do you want this string to be a specific length?

– Andreas Lorenzen
Mar 19 at 22:27




1




1





You do not need to use len to add a leading zero to a string.

– wwii
Mar 19 at 22:27





You do not need to use len to add a leading zero to a string.

– wwii
Mar 19 at 22:27




1




1





What is the expected output?

– solarc
Mar 19 at 22:29





What is the expected output?

– solarc
Mar 19 at 22:29













Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. StackOverflow is not a coding, review, or tutorial resource.

– Prune
Mar 19 at 22:38





Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. StackOverflow is not a coding, review, or tutorial resource.

– Prune
Mar 19 at 22:38












2 Answers
2






active

oldest

votes


















1














If this is "hard coded" to numbers below 10000 and you want 4 total digits, you can simply add 10000 and drop the first character:



rannum = random.randrange(1, 999)
print(str(rannum+10000)[1:])


or more generally speaking:



rannum = random.randrange(1, 999)
digits = 4
print(str(rannum+10**digits)[1:])


another (non-numeric) way of doing it could be:



rannum = random.randrange(1, 999)
digits = 4
print( ("0"*digits+str(rannum))[-digits:] )

# or hard coded:
print( ("0"*4+str(rannum))[-4:] )


and i'm guessing you can't use rjust() either:



print( str(rannum).rjust(4,"0") ) 





share|improve this answer

























  • Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13


















0














I have an answer for you here.



The following script will add a number of leading zeros to the string representation of your random number, always ensuring that it is 3 characters long.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

for x in range(len(rannumStr), 3):
rannumStr = "0" + rannumStr;
print(rannumStr);


In case you want the string longer, just update the second parameter of the range(...) function, like this for 4 characters:



for x in range(len(rannumStr), 4):


Solution without control statements



Based on the comments, I am adding another answer here. This ones does not use any loops, or other control statements like if.



It declares an array of strings, that we can index into using the length of the string representation of the random number. And simply prefix the string with that.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

padding = ["000", "00", "0", ""];

rannumStr = padding[len(rannumStr)] + rannumStr;

print(rannumStr);


I hope that this solves your issue?






share|improve this answer

























  • Thank you very much for your time and effort. Is there any change I could do this without conditional loops (the for x in range), as I have to use very simple python to make this. Again thank you very much and have a great day! :D

    – Bob Singh
    Mar 20 at 9:36











  • Can I use if statements and the len() function?

    – Andreas Lorenzen
    Mar 20 at 11:24











  • I added another solution that does not use loops or if statements. But does make use of the len() function. Let me know if that then can be accepted?

    – Andreas Lorenzen
    Mar 20 at 15:49











  • Yes that is fine. Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55250854%2fadd-leading-zeros-to-a-string-without-zfill-format-loops-or-control-statements%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














If this is "hard coded" to numbers below 10000 and you want 4 total digits, you can simply add 10000 and drop the first character:



rannum = random.randrange(1, 999)
print(str(rannum+10000)[1:])


or more generally speaking:



rannum = random.randrange(1, 999)
digits = 4
print(str(rannum+10**digits)[1:])


another (non-numeric) way of doing it could be:



rannum = random.randrange(1, 999)
digits = 4
print( ("0"*digits+str(rannum))[-digits:] )

# or hard coded:
print( ("0"*4+str(rannum))[-4:] )


and i'm guessing you can't use rjust() either:



print( str(rannum).rjust(4,"0") ) 





share|improve this answer

























  • Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13















1














If this is "hard coded" to numbers below 10000 and you want 4 total digits, you can simply add 10000 and drop the first character:



rannum = random.randrange(1, 999)
print(str(rannum+10000)[1:])


or more generally speaking:



rannum = random.randrange(1, 999)
digits = 4
print(str(rannum+10**digits)[1:])


another (non-numeric) way of doing it could be:



rannum = random.randrange(1, 999)
digits = 4
print( ("0"*digits+str(rannum))[-digits:] )

# or hard coded:
print( ("0"*4+str(rannum))[-4:] )


and i'm guessing you can't use rjust() either:



print( str(rannum).rjust(4,"0") ) 





share|improve this answer

























  • Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13













1












1








1







If this is "hard coded" to numbers below 10000 and you want 4 total digits, you can simply add 10000 and drop the first character:



rannum = random.randrange(1, 999)
print(str(rannum+10000)[1:])


or more generally speaking:



rannum = random.randrange(1, 999)
digits = 4
print(str(rannum+10**digits)[1:])


another (non-numeric) way of doing it could be:



rannum = random.randrange(1, 999)
digits = 4
print( ("0"*digits+str(rannum))[-digits:] )

# or hard coded:
print( ("0"*4+str(rannum))[-4:] )


and i'm guessing you can't use rjust() either:



print( str(rannum).rjust(4,"0") ) 





share|improve this answer















If this is "hard coded" to numbers below 10000 and you want 4 total digits, you can simply add 10000 and drop the first character:



rannum = random.randrange(1, 999)
print(str(rannum+10000)[1:])


or more generally speaking:



rannum = random.randrange(1, 999)
digits = 4
print(str(rannum+10**digits)[1:])


another (non-numeric) way of doing it could be:



rannum = random.randrange(1, 999)
digits = 4
print( ("0"*digits+str(rannum))[-digits:] )

# or hard coded:
print( ("0"*4+str(rannum))[-4:] )


and i'm guessing you can't use rjust() either:



print( str(rannum).rjust(4,"0") ) 






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 22 at 17:30

























answered Mar 20 at 0:07









Alain T.Alain T.

8,70311329




8,70311329












  • Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13

















  • Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13
















Thank you very much! :D

– Bob Singh
Mar 22 at 11:13





Thank you very much! :D

– Bob Singh
Mar 22 at 11:13













0














I have an answer for you here.



The following script will add a number of leading zeros to the string representation of your random number, always ensuring that it is 3 characters long.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

for x in range(len(rannumStr), 3):
rannumStr = "0" + rannumStr;
print(rannumStr);


In case you want the string longer, just update the second parameter of the range(...) function, like this for 4 characters:



for x in range(len(rannumStr), 4):


Solution without control statements



Based on the comments, I am adding another answer here. This ones does not use any loops, or other control statements like if.



It declares an array of strings, that we can index into using the length of the string representation of the random number. And simply prefix the string with that.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

padding = ["000", "00", "0", ""];

rannumStr = padding[len(rannumStr)] + rannumStr;

print(rannumStr);


I hope that this solves your issue?






share|improve this answer

























  • Thank you very much for your time and effort. Is there any change I could do this without conditional loops (the for x in range), as I have to use very simple python to make this. Again thank you very much and have a great day! :D

    – Bob Singh
    Mar 20 at 9:36











  • Can I use if statements and the len() function?

    – Andreas Lorenzen
    Mar 20 at 11:24











  • I added another solution that does not use loops or if statements. But does make use of the len() function. Let me know if that then can be accepted?

    – Andreas Lorenzen
    Mar 20 at 15:49











  • Yes that is fine. Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13















0














I have an answer for you here.



The following script will add a number of leading zeros to the string representation of your random number, always ensuring that it is 3 characters long.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

for x in range(len(rannumStr), 3):
rannumStr = "0" + rannumStr;
print(rannumStr);


In case you want the string longer, just update the second parameter of the range(...) function, like this for 4 characters:



for x in range(len(rannumStr), 4):


Solution without control statements



Based on the comments, I am adding another answer here. This ones does not use any loops, or other control statements like if.



It declares an array of strings, that we can index into using the length of the string representation of the random number. And simply prefix the string with that.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

padding = ["000", "00", "0", ""];

rannumStr = padding[len(rannumStr)] + rannumStr;

print(rannumStr);


I hope that this solves your issue?






share|improve this answer

























  • Thank you very much for your time and effort. Is there any change I could do this without conditional loops (the for x in range), as I have to use very simple python to make this. Again thank you very much and have a great day! :D

    – Bob Singh
    Mar 20 at 9:36











  • Can I use if statements and the len() function?

    – Andreas Lorenzen
    Mar 20 at 11:24











  • I added another solution that does not use loops or if statements. But does make use of the len() function. Let me know if that then can be accepted?

    – Andreas Lorenzen
    Mar 20 at 15:49











  • Yes that is fine. Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13













0












0








0







I have an answer for you here.



The following script will add a number of leading zeros to the string representation of your random number, always ensuring that it is 3 characters long.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

for x in range(len(rannumStr), 3):
rannumStr = "0" + rannumStr;
print(rannumStr);


In case you want the string longer, just update the second parameter of the range(...) function, like this for 4 characters:



for x in range(len(rannumStr), 4):


Solution without control statements



Based on the comments, I am adding another answer here. This ones does not use any loops, or other control statements like if.



It declares an array of strings, that we can index into using the length of the string representation of the random number. And simply prefix the string with that.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

padding = ["000", "00", "0", ""];

rannumStr = padding[len(rannumStr)] + rannumStr;

print(rannumStr);


I hope that this solves your issue?






share|improve this answer















I have an answer for you here.



The following script will add a number of leading zeros to the string representation of your random number, always ensuring that it is 3 characters long.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

for x in range(len(rannumStr), 3):
rannumStr = "0" + rannumStr;
print(rannumStr);


In case you want the string longer, just update the second parameter of the range(...) function, like this for 4 characters:



for x in range(len(rannumStr), 4):


Solution without control statements



Based on the comments, I am adding another answer here. This ones does not use any loops, or other control statements like if.



It declares an array of strings, that we can index into using the length of the string representation of the random number. And simply prefix the string with that.



import random;

rannum = random.randrange(1, 999)
rannumStr = str(rannum);

padding = ["000", "00", "0", ""];

rannumStr = padding[len(rannumStr)] + rannumStr;

print(rannumStr);


I hope that this solves your issue?







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 20 at 15:48

























answered Mar 19 at 22:32









Andreas LorenzenAndreas Lorenzen

1,076412




1,076412












  • Thank you very much for your time and effort. Is there any change I could do this without conditional loops (the for x in range), as I have to use very simple python to make this. Again thank you very much and have a great day! :D

    – Bob Singh
    Mar 20 at 9:36











  • Can I use if statements and the len() function?

    – Andreas Lorenzen
    Mar 20 at 11:24











  • I added another solution that does not use loops or if statements. But does make use of the len() function. Let me know if that then can be accepted?

    – Andreas Lorenzen
    Mar 20 at 15:49











  • Yes that is fine. Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13

















  • Thank you very much for your time and effort. Is there any change I could do this without conditional loops (the for x in range), as I have to use very simple python to make this. Again thank you very much and have a great day! :D

    – Bob Singh
    Mar 20 at 9:36











  • Can I use if statements and the len() function?

    – Andreas Lorenzen
    Mar 20 at 11:24











  • I added another solution that does not use loops or if statements. But does make use of the len() function. Let me know if that then can be accepted?

    – Andreas Lorenzen
    Mar 20 at 15:49











  • Yes that is fine. Thank you very much! :D

    – Bob Singh
    Mar 22 at 11:13
















Thank you very much for your time and effort. Is there any change I could do this without conditional loops (the for x in range), as I have to use very simple python to make this. Again thank you very much and have a great day! :D

– Bob Singh
Mar 20 at 9:36





Thank you very much for your time and effort. Is there any change I could do this without conditional loops (the for x in range), as I have to use very simple python to make this. Again thank you very much and have a great day! :D

– Bob Singh
Mar 20 at 9:36













Can I use if statements and the len() function?

– Andreas Lorenzen
Mar 20 at 11:24





Can I use if statements and the len() function?

– Andreas Lorenzen
Mar 20 at 11:24













I added another solution that does not use loops or if statements. But does make use of the len() function. Let me know if that then can be accepted?

– Andreas Lorenzen
Mar 20 at 15:49





I added another solution that does not use loops or if statements. But does make use of the len() function. Let me know if that then can be accepted?

– Andreas Lorenzen
Mar 20 at 15:49













Yes that is fine. Thank you very much! :D

– Bob Singh
Mar 22 at 11:13





Yes that is fine. Thank you very much! :D

– Bob Singh
Mar 22 at 11:13

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55250854%2fadd-leading-zeros-to-a-string-without-zfill-format-loops-or-control-statements%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Obelisk of Theodosius Contents History Description Notes Bibliography Further reading External links Navigation menuAge of spirituality : late antique and early Christian art, third to seventh centuryOver 60 picturesObelisks of the World41°00′21.24″N 28°58′31.43″E / 41.0059000°N 28.9753972°E / 41.0059000; 28.97539727724550-7235741376235741376

밀양 대씨 역사 각주 함께 보기 둘러보기 메뉴밀양 대씨

1973년 목차 사건 문화 탄생 사망 노벨상 달력 둘러보기 메뉴