[Tutor] Replacing characters

Kent Johnson kent37 at tds.net
Fri May 25 16:20:44 CEST 2007


Per Jr. Greisen wrote:
> Hi,
> 
> I am replacing 4 characters with a number and I would like to make the 
> whitespace dynamic so
> for fx. 1 it uses 3 whitespace and for 10 two and for 100 one etc. I am 
> using the replace() method.

I'm not too sure what you want to do but probably str.rjust() or a 
format string with a width parameter will do what you want:

In [16]: nums = [1, 10, 100, 1000]
In [17]: for num in nums:
    ....:     print str(num).rjust(4)
    ....:
    ....:
    1
   10
  100
1000
In [18]: for num in nums:
    ....:     print '%4d' % num
    ....:
    ....:
    1
   10
  100
1000

Details here:
http://docs.python.org/lib/string-methods.html
http://docs.python.org/lib/typesseq-strings.html

Kent


More information about the Tutor mailing list