Hi Mike,

While not technically deprecated, use of the `%` operator is discouraged in favor of the more powerful and more clear `format` function.  The string presentation syntax of `%{some_character}` has a legacy rooted in C and other statically typed languages.  Python is very dynamic and when possible it will try to "do what you mean" rather than being pedantic about variable types.  The documentation for what all the various string presentations types are is here:

https://docs.python.org/2/library/string.html#format-specification-mini-language

but there's a few your probably mostly concerned with:

%r - raw (let python figure it out)
%s - string
%d - integer (d is for decimal integer)
%f - float (default is 6 decimal places)

Traditionally in C-like statically typed languages swapping %d for %s would cause an error, because Python supports dynamic typing, when it sees the `%s` it expects a string and converts your numeric value to a string automatically.  There's certain cases where python can't guess what you mean and it blows up:

    >>> print "Hello world!"
    Hello world!
    >>> print "Hello %r!" % "world"
    Hello 'world'!
    >>> print "Hello %s!" % "world"
    Hello world!
    >>> print "Hello %d!" % "world"
    
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        print "Hello %d!" % "world"
    TypeError: %d format: a number is required, not str
    >>> print "Hello {0}!".format("world")
    Hello world!

`%r` will pretty much always work, `%s` was fine because "world" is already a string.  Using `%d` lead to an error because "world" has no clear meaning as an integer.  Finally the `.format` method is the now preferred approach and it uses `{0}` to mean the first argument (something like `%r` is implied automatically).

In general the trick to understanding these sorts of errors and behaviors is to realize that all expressions have a type even if you don't explicitly set them:

    >>> type(1)
    <type 'int'>
    >>> type("world")
    <type 'str'>
    >>> type(1.00)
    <type 'float'>
    >>> def greet(name):
print "Hello {0}".format(name)

    >>> type(greet)
    <type 'function'>

Some types can be implicitly converted (almost anything will convert to a string), others won't convert so easy (like "world" to an integer).



On Sat, Oct 11, 2014 at 12:34 PM, Michael Havens <bmike1@gmail.com> wrote:
Well, I've decided to try to learn python. Right now I'm on 'format string'.So there are different ones, right? Well, I'm working with %d and %s right now and if I change the %d to a %s I get the same result when I run the program. My question  is %x just a place holder or do they have special meanings?
:-)~MIKE~(-:

---------------------------------------------------
PLUG-discuss mailing list - PLUG-discuss@lists.phxlinux.org
To subscribe, unsubscribe, or to change your mail settings:
http://lists.phxlinux.org/mailman/listinfo/plug-discuss



--
Paul Mooring
Operations Team Lead
Chef