Page 221 -
P. 221
real-world format strings
The Format String Exposed
This week’s interview:
Why do appearances matter?
Head First: Format String, it’s a pleasure to meet code and creating strings manually. But I don’t think
you. that’s a great idea.
Format String: The pleasure is all mine. Head First: Why’s that?
Head First: You’re not just used in Python, are Format String: Two reasons: first, you might have
you? to create a lot of code, and second, I’m a little more
dynamic.
Format String: Oh no. I’m really used in lots of
programming languages, like C, C#, and Java. You Head First: What do you mean?
see me crop up all over the place.
Format String: Well, I’m just data. Lots of times,
Head First: Why is that? programmers prefer to use data instead of chunks
of code, because it means they can store me away
Format String: Well, I don’t like to blow my own as configuration. So I get used a lot for things like
bugle, but I am kind of useful. Everywhere you need internationalization.
to generate formatted text, I can make life a lot easier
for you. Head First: Internationalization?
Head First: Can you give us some examples? Format String: Yeah, say someone wants to display
a message that someone has the top score. They
Format String: Oh sure. If you need to send data could write the message in a file like “%d is the top
to another system, you’ll probably need me. If you score!”. If they write a French version of the game,
want to display an error message in a specific format, they just have to amend me to “%d est les points
I’m good at that, too.
supérieurs!”
Head First: I hate to say this, it seems so rude, but Head First: No code change necessary.
isn’t it possible to do everything you do with just
normal string operations? Format String: Exactly.
Format String: Please, I don’t take offence. Yes, Head First: String Format, thanks for your time.
you can do pretty much everything I do by writing
Q: Those format strings look a little Q: Are there special rules for what’s Q: Why does the code generate the
weird. How do I find out more about acceptable as a credit card number? menu in such a complex way?
them?
A: Yes, there are. But let’s not get A: If you study the menu generation
A: A good reference book (we present bogged down in those type of details at this code, you will see that when you add more
our favorite in the appendix) will contain all stage. Concentrate on the items and prices, the rest of the code
you need to know and there’s also lots of save_transaction() function doesn’t need to change to support the new
material on-line in the official Python docs. and how the code interacts with it. items.The menu is generated automatically.
186 Chapter 6