If you like what you're reading here, you can find it at Wrox or purchase the entire book at Amazon. Putting Strings Together in Different Ways Another way to specify strings is to use a format specifier. It works by putting in a special sequence of characters that Python will interpret as a placeholder for a value that will be provided by you. This may initially seem like it’s too complex to be useful, but format specifiers also enable you to control what the displayed information looks like, as well as a number of other useful tricks. Try It Out: Using a Format Specifier to Populate a String In the simplest case, you can do the same thing with your friend, John Q.: > > > “John Q. %s” % (“Public”) ‘John Q. Public’
The %s is known as a format specifier, specifically for strings. As the discussion on data types continues throughout this book, you take a look at several more, each specific to its given data type. Every specifier acts as a placeholder for that type in the string; and after the string, the % sign outside of the string indicates that after it, all of the values to be inserted into the format specifier will be presented there to be used in the string. You may notice the parentheses. This tells the string that it should expect to see a sequence that contains the values to be used by the string to populate its format specifiers. A simpler way to think of it is to imagine that the %s is a storage bin that holds the value in the parentheses. If you want to do more than one value, you would simply add another format specifier, in this manner:
John Everyman
So why do they call it a format specifier if you store data in it? The reason is that it has multiple functions; being a container is only one of them. The following example shows you how to not only store data with the format specifier, but specify how that data will be displayed as well.
blog comments powered by Disqus |