If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting
Copy>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'
See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings
Here is an example with variable width
Copy>>> '{num:0{width}}'.format(num=123, width=6)
'000123'
You can even specify the fill char as a variable
Copy>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
Answer from John La Rooy on Stack OverflowGeneral way to print floats without the .0 part
How do I put commas between numbers?
Videos
If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting
Copy>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'
See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings
Here is an example with variable width
Copy>>> '{num:0{width}}'.format(num=123, width=6)
'000123'
You can even specify the fill char as a variable
Copy>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
There is a string method called zfill:
Copy>>> '12344'.zfill(10)
0000012344
It will pad the left side of the string with zeros to make the string length N (10 in this case).
Let's say I have 2792819, now I want it to be like 2,792,819. How do I do it?
I can do so while reversing it and after every 3 iterations, put a comma or something like that. But is there a better way to do so?