Jump to content

Is this an error in my book on Format specifier?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
live504

live504

    Newbie

  • Members
  • PipPip
  • 12 posts
In the book Beginning Python by James Payne it says "Whenever you right a negative (-) in your format specifier, the format occurs to the left of the word. If there is just a number with no negative it occurs to the right".

Well.... I must not understand what he means, or there must be an error in his writing. When I type the first example with the negative, it moves to the right. In the second, it moves to the left.

I also noticed that he wrote right instead of write, so this whole sentence might be an error.

>>> "%-30s %s" % ("Hello", "Hi")
'Hello______________________________Hi'

>>> "%30s %s" % ("Hello", "Hi")
'______________________________Hello Hi'
The underlines represent spaces, the spaces don't show on the post if I don't underline the area.

Edited by live504, 03 July 2010 - 08:50 PM.


#2
CatatonicMan

CatatonicMan

    Newbie

  • Members
  • PipPip
  • 13 posts
There might be an error, or there might just be an issue with clarity. Either way, you now know what Python is going to do, so the issue takes care of itself.

#3
Warrior

Warrior

    Programmer

  • Members
  • PipPipPipPip
  • 130 posts
There's not any error though,the interpreter is doing just as the writer said!

If you put a '-' in the format specifier then the logic is as follows:-


import sys


fs=6        #The number after -

c=fs-len("hello")      

if c>0:

  for i in range(c):

    sys.stdout.write(' ') #Write a space c times


Warrior
Be a joke unto yourself!
Check out my blog at Flashcore

#4
manux

manux

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 234 posts
When you use %30s in your format, I think, it will try to use at most 30 characters, and when your string is less than 30 characters, fill it with spaces. So when there's a "-" before the 30, it will fill it with zeros before writing it, instead of after. That's what he means by, "the format will occur to the left/right".