tags:

views:

101

answers:

6

Pretty much what it says up there.

Basically, how do I get the string produced by

print "%05d" % 100
+1  A: 

Use str.zfill(width)

deworde
The URL for zfill is http://docs.python.org/library/stdtypes.html#str.zfill. The % or format techniques are preferred.
GreenMatt
+10  A: 

Maybe I'm misinterpreting the question, but this should work:

my_string = "%05d" % 100
Bruno
Huh. Assumed that was part of the args to print. Nope. God, it's a beautiful language.
deworde
@deworde: It's even better if you read through a tutorial. Seriously. What tutorial are you using?
S.Lott
+1 for the nice answer badge
gnibbler
@S.Lott I'm looking at http://docs.python.org/tutorial/introduction.html#strings right now.And that doesn't tell you it's in there, and when it gives you an example in the reference notes, always uses print.
deworde
@deworde: Thanks. There's a "See Also" section that's relevant. You might want to use http://diveintopython.org/native_data_types/formatting_strings.html instead.
S.Lott
@S.Lott Yes, that would be the reference notes I referred to, but as I said, always uses print in the examples.Also, they're, as usual, in a style that means you have to know what you're looking for before you start looking. My favourite line, "The effect is similar to the using sprintf() in the C language". I mean technically, that should have been helpful, but it does rather make an assumption.
deworde
@S.Lott Cheers for the link, though. V. helpful.
deworde
+1  A: 

This should work too:

`100`.zfill(5)
Tarantula
A: 

If you're using Python 3, the str.format method is preferred. It was introduced in Python 2.6. (Alas, my work system is at 2.4 (and I'm not permitted to upgrade), so I can't construct and test an example.)

GreenMatt
+1  A: 
print('{0:0=5d}'.format(100))
# 00100


    use the 0th positional argument to format
   /  fill character is '0'
  /  / desired width of formatted string
 /  / /
{0:0=5d}

For more, see the docs.

unutbu
+1  A: 
i = 100
str(i).zfill(5)
FlowofSoul