[Tutor] Replacing characters

2007-05-25 Thread Per Jr. Greisen

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.

Any help or advice appreciated

Thanks in advance
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replacing characters

2007-05-25 Thread Kent Johnson
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
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor