473,387 Members | 1,303 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

left padding zeroes on a string...

cjl
Hey all:

I want to convert strings (ex. '3', '32') to strings with left padded
zeroes (ex. '003', '032'), so I tried this:

string1 = '32'
string2 = "%03s" % (string1)
print string2
32
This doesn't work. If I cast string1 as an int it works:

string1 = '32'
int2 = "%03d" % (int(string1))
print int2
032


Of course, I need to cast the result back to a string to use it. Why
doesn't the first example work?

-cjl

Jul 18 '05 #1
11 25702
cjl wrote:
Hey all:

I want to convert strings (ex. '3', '32') to strings with left padded
zeroes (ex. '003', '032'), so I tried this:

string1 = '32'
string2 = "%03s" % (string1)


string1.zfill(3)

-Peter
Jul 18 '05 #2
"cjl" <cj****@gmail.com> wrote:
Hey all:

I want to convert strings (ex. '3', '32') to strings with left padded
zeroes (ex. '003', '032'), so I tried this:

string1 = '32'
string2 = "%03s" % (string1)
print string2
32
This doesn't work.


Actually in this case string2 is padded with spaces, instead of zeros.
If I cast string1 as an int it works:

string1 = '32'
int2 = "%03d" % (int(string1))
print int2
032
Of course, I need to cast the result back to a string to use it. Why
doesn't the first example work?


That's not correct; int2 is a string so you can use it directly (and probably rename it to something
more appropriate).
-cjl


Regards,
George
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"To see victory only when it is within the ken of the common herd is not
the acme of excellence."

Sun Tzu, 'The Art of War'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Jul 18 '05 #3
Your first conversion works fine.
string1 = '32'
string2 = "%04s" % (string1)
print string2
' 32'
Notice that it returns a string with spaces padding the left side.
If you want to pad a number with 0's on the left you need to use
zfill()
'32'.zfill(4)
'0032'
Be sure to study up on string methods, it will save you time and
sanity.
Py> dir('')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__',
'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__',
'__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
Py> help(''.zfill)
Help on built-in function zfill:

zfill(...)
S.zfill(width) -> string

Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
Hth,
M.E.Farmer

Jul 18 '05 #4

cjl wrote:
I want to convert strings (ex. '3', '32') to strings with left padded
zeroes (ex. '003', '032'), so I tried this:

string1 = '32'
string2 = "%03s" % (string1)
print string2
32
This doesn't work.


Documentation == """
Flag Meaning
0 The conversion will be zero padded for numeric values.
"""

"Numeric values" means when converting from a numeric value as in
"%03d", but not "%03s". If you think "numeric values" is vague or
misleading -- K&R (v2 p243) has "numeric conversions" -- then submit a
documentation patch.
If I cast string1 as an int it works:


Python doesn't have casts. You mean "convert".

You may like to consider the zfill method of string objects:
"3".zfill(5) '00003'

or the even more versatile rjust method:
"3".rjust(5, '0') '00003' "3".rjust(5, '*') '****3'


HTH,
John

Jul 18 '05 #5
cjl wrote:
Hey all:

I want to convert strings (ex. '3', '32') to strings with left padded
zeroes (ex. '003', '032')


In Python 2.4 you can use rjust with the optional fill argument:
'3'.rjust(3, '0') '003'

In earlier versions you can define your own: def rjust(s, l, c): ... return ( c*l + s )[-l:]
... rjust('3', 3, '0') '003' rjust('32', 3, '0')

'032'

Kent
Jul 18 '05 #6
"M.E.Farmer" <me*****@hotmail.com> wrote:

[snipped]

Be sure to study up on string methods, it will save you time and
sanity.
Py> dir('')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__',
'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__',
'__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']


I'm getting off-topic here, but it strikes me that strings have so many methods (some of which are
of arguable utility, e.g. swapcase), while proposing two useful methods (http://tinyurl.com/5nv66)
for dicts -- a builtin with a considerably smaller API than str -- meets so much resistance. Any
insight ?

George
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"Oh divine art of subtlety and secrecy! Through you we learn to be
invisible, through you inaudible and hence we can hold the enemy's fate
in our hands."

Sun Tzu, 'The Art of War'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Jul 18 '05 #7
Once it is in everyone is hesitant to take it out for fear of
breaking someone's code that uses it (no matter how obscure).
Putting in new methods should be difficult and require lots
of review for that reason and so we don't have language bloat.

Larry Bates
George Sakkis wrote:
"M.E.Farmer" <me*****@hotmail.com> wrote:
[snipped]

Be sure to study up on string methods, it will save you time and
sanity.
Py> dir('')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__',
'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__',
'__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']

I'm getting off-topic here, but it strikes me that strings have so many methods (some of which are
of arguable utility, e.g. swapcase), while proposing two useful methods (http://tinyurl.com/5nv66)
for dicts -- a builtin with a considerably smaller API than str -- meets so much resistance. Any
insight ?

George
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"Oh divine art of subtlety and secrecy! Through you we learn to be
invisible, through you inaudible and hence we can hold the enemy's fate
in our hands."

Sun Tzu, 'The Art of War'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Jul 18 '05 #8
"Larry Bates" <lb****@syscononline.com> wrote in message news:YO********************@comcast.com...
Once it is in everyone is hesitant to take it out for fear of
breaking someone's code that uses it (no matter how obscure).
Putting in new methods should be difficult and require lots
of review for that reason and so we don't have language bloat.

Larry Bates


Language bloat is subjective of course, but I fail to see why putting in dict.reset and dict.add
should be harder than, say, str.swapcase or str.capitalize.

George


Jul 18 '05 #9
George Sakkis wrote:
"Larry Bates" <lb****@syscononline.com> wrote in message news:YO********************@comcast.com...
Once it is in everyone is hesitant to take it out for fear of
breaking someone's code that uses it (no matter how obscure).
Putting in new methods should be difficult and require lots
of review for that reason and so we don't have language bloat.

Larry Bates

Language bloat is subjective of course, but I fail to see why putting in dict.reset and dict.add
should be harder than, say, str.swapcase or str.capitalize.


Those were functions in the string module for, well much longer than I
can remember. When string methods were innovated, they became methods
along with the rest of the string module functions.

Adding functions was easier back then; the standard library was rather
smaller. There is no reason that the criteria for inclusion now must be
the same as then and plenty of good reasons for them to be more
restrictive now.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
Jul 18 '05 #10
On Fri, 25 Mar 2005 18:06:11 -0500, "George Sakkis"
<gs*****@rutgers.edu> wrote:

I'm getting off-topic here, but it strikes me that strings have so many methods (some of which are
of arguable utility, e.g. swapcase), while proposing two useful methods (http://tinyurl.com/5nv66)
for dicts -- a builtin with a considerably smaller API than str -- meets so much resistance. Any
insight ?

George


I did a quick check.
len(dir(str)) 63 len(dir(int)) 53 len(dir(float)) 45 len(dir(dict)) 40 len(dir(list)) 42 len(dir(tuple))

27

We need more tuple methods! jk ;)

Looks like the data types, strings, int an float; have more methods
than dict, list, and tuple. I would expect that because there is more
ways to manipulate data than is needed to manage containers.

Ron
Jul 18 '05 #11
On Sat, 26 Mar 2005 04:10:21 GMT, Ron_Adam <ra****@tampabay.rr.com> wrote:
On Fri, 25 Mar 2005 18:06:11 -0500, "George Sakkis"
<gs*****@rutgers.edu> wrote:

I'm getting off-topic here, but it strikes me that strings have so many methods (some of which are
of arguable utility, e.g. swapcase), while proposing two useful methods (http://tinyurl.com/5nv66)
for dicts -- a builtin with a considerably smaller API than str -- meets so much resistance. Any
insight ?

George


I did a quick check.
len(dir(str))63 len(dir(int))53 len(dir(float))45 len(dir(dict))40 len(dir(list))42 len(dir(tuple))27

We need more tuple methods! jk ;)

Looks like the data types, strings, int an float; have more methods
than dict, list, and tuple. I would expect that because there is more
ways to manipulate data than is needed to manage containers.

More data:
for n,k in sorted((len(dir(v)),k) for k,v in ((k,v) for k,v in vars(__builtins__).items() ... if isinstance(v, type))): print '%4s: %s' %(n,k)
...
12: basestring
12: object
13: classmethod
13: staticmethod
14: enumerate
15: reversed
16: super
16: xrange
17: slice
18: property
23: buffer
27: tuple
27: type
34: file
34: open
37: frozenset
40: dict
42: list
45: float
48: complex
50: set
53: bool
53: int
53: long
60: unicode
63: str

Hm, I guess that includes inheritance, and they should be callable, so maybe (not researched)
for n,k in sorted((sum(callable(m) for k,m in vars(v).items()),k)

... for k,v in ((k,v) for k,v in vars(__builtins__).items()
... if isinstance(v, type))): print '%4s: %s' %(n,k)
...
1: basestring
4: classmethod
4: enumerate
4: staticmethod
5: reversed
5: super
6: property
6: slice
7: xrange
9: bool
10: object
10: type
16: buffer
19: tuple
22: file
22: open
30: frozenset
33: dict
35: list
38: float
39: complex
44: set
46: int
46: long
53: unicode
56: str

Regards,
Bengt Richter
Jul 18 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: RA | last post by:
Hi When I create a table and aligned it to the left, how can I have some padding added from the left so that the user will see the table border on the left? I don't want to use the vs style...
1
by: geniolatenio | last post by:
Hello guys, I have a rather strange problem with IE (googled for it to no avail) I have these two styles in the css file, right? #menu { left:13px; padding:13px 0 14px 247px;...
2
by: voam | last post by:
Hi, I come from a VB background and often to prepare a string for insertion into a database I would make sure that the length of the string did not exceed the size of varchar that the database...
2
by: mmrz | last post by:
what is a function which I can use for filling a remain string variable with space. for example X variable is as a string and it can have 16 length but if it has for example "ABCDEF" value I want it...
6
by: maya | last post by:
hi, I recently discovered the hard way that when you had padding-right or padding-left to a div it increases the with of the div... how do you add left-padding or right-padding to a div w/o...
1
by: rajesh kataraki | last post by:
Hello, My requirement is I am using one variable ex. var = 5 which is integer. And this variable, I m using in some string. But I want this var to be used as 005 again integer in this string. ...
41
by: nospam | last post by:
If I have a string say: myvar = "This is a string"; How do I use sprintf to convert the string so it has 4 spaces padded on the left like:
2
overcomer
by: overcomer | last post by:
Hi.... Please advise on how to create dynamic left padding for string... thanks to you.. Also, if anyone could add any idea of cascading combo box as it's not possible to setup rowsource in...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.