Skip to content
Fix Code Error

Display number with leading zeros

March 13, 2021 by Code Error
Posted By: jeff

Given:

a = 1
b = 10
c = 100

How do I display a leading zero for all numbers with less than two digits?

This is the output I’m expecting:

01
10
100

Solution

In Python 2 (and Python 3) you can do:

print "%02d" % (1,)

Basically % is like printf or sprintf (see docs).


For Python 3.+, the same behavior can also be achieved with format:

print("{:02d}".format(1))

For Python 3.6+ the same behavior can be achieved with f-strings:

print(f"{1:02d}")
Answered By: Jack M.

Related Articles

  • Determine Number of Trailing Zeros of a Factorial…
  • Getting infinite loop after entering 2 objects to…
  • Quickly getting to YYYY-mm-dd HH:MM:SS in Perl
  • How to convert milliseconds to "hh:mm:ss" format?
  • Adding leading zeros inbetween mixed strings
  • How to add leading zeros?
  • SDL_SetRenderTarget() hangs for a while if multiple…
  • Printf width specifier to maintain precision of…
  • OpenCL - Approximation of Pi via Monte Carlo…
  • Avoid trailing zeroes in printf()
  • Validate that a string is a positive integer
  • Examples of GoF Design Patterns in Java's core libraries
  • How to get year, month, day, hours, minutes, seconds…
  • How do I determine whether my calculation of pi is accurate?
  • dynamically set decimal separator in number/string…
  • C compile error: Id returned 1 exit status
  • Design DFA accepting binary strings divisible by a…
  • PHP prepend leading zero before single digit number,…
  • What are the undocumented features and limitations…
  • Why does C++ code for testing the Collatz conjecture…
  • How to generate a random string of a fixed length in Go?
  • ERROR 1396 (HY000): Operation CREATE USER failed for…
  • Use v-model with a checkbox when v-for is used with…
  • Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM
  • Palindromic numbers in Java
  • What is a plain English explanation of "Big O" notation?
  • Query based on multiple where clauses in Firebase
  • What are the new features in C++17?
  • delete item in array of struct that has char array…
  • Simple C example of doing an HTTP POST and consuming…
  • fork() and wait() with two child processes
  • Finding all possible combinations of numbers to…
  • Custom format for time command
  • VueJS: Getting values from multiple checkbox binding…
  • How to solve the problem in Javascript code to…
  • ValueError: could not broadcast input array from…
  • How to append strings using sprintf?
  • How to print a number with commas as thousands…
  • Operator '+' cannot be applied to 'java.lang.String'…
  • Regular expression to match numbers with or without…
  • Controlling number of decimal digits in print output in R
  • Continuous Convolution Using 3 Different Methods in…
  • How can I configure Storybook.js Webpack with…
  • Remove leading zeros from a number in Javascript
  • Using less in a polymer-dart application
  • Creating C formatted strings (not printing them)
  • Using floats with sprintf() in embedded C
  • How to write an application to control a driver…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Leading zeros for Int in Swift
  • Uncheck CheckBox with its label in VueJS
  • Easy interview question got harder: given numbers…
  • Automatic loop termination
  • How to truncate float values?
  • Current time formatting with Javascript
  • JavaScript math, round to two decimal places
  • Implementation of user defined array on stack and/or…
  • JavaScript gives NaN error on the page but variable…
  • How do you detect Credit card type based on number?
  • How to remove leading and trailing zeros in a string? Python
  • Why is my loop stopping at the first argument (char…
  • Can't install via pip because of egg_info error
  • PHP is_numeric or preg_match 0-9 validation
  • Java string to date conversion
  • Fastest way to iterate over all the chars in a String
  • python how to pad numpy array with zeros
  • problem with client server unix domain stream…
  • How to check that a string is parseable to a double?
  • Decimal or numeric values in regular expression validation
  • Active tab issue on page load HTML
  • How to match an optional entire phone number using…
  • How to format a phone number in a textfield
  • How to prevent scrolling the whole page?
  • How the int.TryParse actually works
  • How to print a date in a regular format?
  • replacing list items in reverse order and skipping…
  • How is printf printing 53 digits after decimal point?
  • Returning a C string from a function
  • Question about memory allocation for literal strings in c
  • How to render the append string to html using react hooks
  • Searching for matching elements between 2 arrays in C
  • format string in javascript
  • Increasing size of semi circle using css
  • How does PHP 'foreach' actually work?
  • Hard fault on sprintf() with float after toolchain update
  • How do you convert a byte array to a hexadecimal…
  • Reference - What does this regex mean?
  • Getting the closest string match
  • Is there any possible way to loop strcmp function in…
  • How to verify strings and doubles in switch satements
  • How to convert number to words in java
  • Start redis-server with config file
  • Find string( js search and regex) with backslashes…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Siemens LOGO! PLC data in the wrong order
  • Why does declared array size not affect the size of…
  • Is there a way to generate 10 numbers per row?
  • Segmentation Fault: (Core dumped) while trying to…
  • How to output numbers with leading zeros in JavaScript?
  • Is it possible to apply CSS to half of a character?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Java Hashmap: How to get key from value?

Next Post:

How to run a hello.js file in Node.js on windows?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error