Use strings to format strings

Many programs need to create strings with particular pieces of data at particular places, so most computer languages try to make life easier for you by letting you use string formats.

The best way to understand string formats is with an example. Open up the Python SM and type in this: The first value will be inserted as a ■ ^-character number.

>>> print("There are available" %

There are

17 donuts available r

17 donuts available

The number has extra spaces added at the front, to make sure it takes up the required 5 characters.

When Python sees a string followed by a percentage (%) symbol, it knows that it needs to consider the string as a string format. The values that follow the % operator are going to be inserted into the formatted string in the order specified, one value at a time. Wherever Python finds a % inside the string, it knows to insert a value.

specification %5d

The second value will be inserted as a string-

"donuts"))

The string-formatting operator

When Python sees this, it will insert the value 17 as a 5-character whole number—that's because the "d" type specifier tells Python to print the number as a decimal. Because 17 is not 5-characters long, Python will left-pad it with 3 extra spaces at the front to make it the correct length.

f\ string formât^ specification

This symbol tells Python to insert the value "donuts" as a string. As you are not specifying a length here, the string is inserted as is.

These are just two examples of how to format values in a string. There are lots more.

Match each format string to what it does. We've already done one for you.

1 %s %e" % ("Value is", 16.0 ** 0.5) Display a string followed by 4.000000.

'%s is $%4.2f" % ("Popsicle", 1.754)

Display a string followed by 4.000000e+00.

Display the value, padded with 0s.

Display the result of the calculation, padded with spaces.

Pad the string out to 20 characters, then display a newline character.

' %s %f" % ("Value is", 16.0 ** 0.5) Display the number as a hexidecimal (base 16).

As well as a string, also display a floating point number to 2 decimal places.

Look back at the records you need to create for the transaction file. Each line will need to end with a newline character. If you have the credit card number, price, and description in variables decimal poiht in • called credit card, price, and description, write down what you would use for the format string:

format string

If you have just one value to format, you don't need to surround it with parentheses.

You were to match each format string to what it does.

"%s %e" % ("Value is", 16.0 ** 0.5)

H\n means take a NEWLINE

"%20s\n" % This means "use 4 characters

This means "shov after the decimal

Following the % with a 0 means "pad with zeroes."

"%s %e" % ("Value is", 16.0 ** 0.5)

Display a string followed by 4.000000e+00.

Display the value, padded with 0s.

Display the number as a hexidecimal (base 16).

Display a string followed by 4.000000.

Display a string followed by 4.000000e+00.

Display the value, padded with 0s.

Display the result of the calculation, padded with spaces. ^__jj default, Py^on ^ ?ad using spaces.

Pad the string out to 20 characters, then display a newline character.

Display the number as a hexidecimal (base 16).

As well as a string, also display a floating point number to 2 decimal places.

are used -for things like Colors on the Welo-

D0n't worry if your answer doesn't look EXACTLY like this. Try out your answer in the Python Shell to check that it works.

You were to look back at the records you need to create for the transaction file and write down what you would use for the format string:

displaying it as a whole number effectively removes the decimal point from the price.

7o|6s%07d%|6sV % (credit_card, price*l00, description)

Cvedit card numbers should always be exactly 16 characters.

You need a newline character at the end of each line.

Code Magnets

Now that you know how to format the records in the transactions . txt file, it is time to write the rest of the coffee bar POS program. Complete the code below by arranging the code magnets in the correct place:

The "a" means you are always def save_transaction(price, credit_card, description) : going to APPEND reCords file = open("transactions.txt", "a")

to the end of the file.

file.write("%s%07d%s\n" % (credit_card, price * 100, description)) file.close ( )

This is the format string you just created.

items = ["DONUT", "LATTE", "FILTER", "MUFFIN"] prices = [1.50, 2.0, 1.80, 1.20] running = True

The loop will keep running while the "running" variable has the while running: ^---' ^ True. To end the loop, set option = 1 "running" to False.

for choice in items:

option = option + 1 print(str(option) + ". Quit")

if choice == option:

new pos program

Code Magnets Solution

Now that we know how to format the records in the transactions . txt file, it is time to write the rest of the coffee bar POS program. You were to complete the code below by arranging the code magnets:

def save_transaction(price, credit_card, description): file = open("transactions.txt", "a")

file.write("%s%07d%s\n" % (credit_card, price * 100, description)) file.close()

items = ["DONUT", "LATTE", "FILTER", "MUFFIN"]

prices = [1.50, 2.0, 1.80, This is the matching array of menu prices.

running = True while running: option = 1

^This code displays the Program's menu.

while running: option = 1

I___^The user enters a menu

| choice = int(input("Choose an option: ")T~|

if choice == option:

' his wil1 be True if the user selects the LAST

running = False 1 0ption 0n the menu, which is "Quit"

else:

credit_card = input("Credit card number: ") ^

save_transaction(prices[choice - 1], credit_card, [ 1tems[choice - jj

Tqst Drivq

The machine has been set up in the coffee bar just in time for the boss to come in for his morning latte, so let's run the code and see what he thinks. Run the program in IDLE:

The sales are recorded in the transactions.txt f'i|e.

The sales are recorded in the transactions.txt f'i|e.

The newline character . makes sure the sales arc reCorded on separate lines. (YoU can't see then in the file, but they are there.)

Fourni J, 0.1 (ïïllïïgMÏ, Ici IT 2«09. IM)iSl| [0& 4.3.2] or. lima«

Typ- "mpjrtijhf, "L-riiiSLL*- LIT -PLL:nnB^||_ TEIT buih LnTun

HUTTIt) Qtkth

Credit Eire lui^iwc; iJt2 7*Si)»7iJB3J H^R LATTE FIITEB Ml" [31 J. IJUlL

I'hEHinn nn njhl.Nrai: 1 L'rvjit czzi aulKE:

The program displays a list of items for sale and when you choose one and provide a credit card number, it adds the sale into a file called transactions . txt. This is the same file that the POS system in the gym uses.

The newline character . makes sure the sales arc reCorded on separate lines. (YoU can't see then in the file, but they are there.)

The boss agrees to try out the system in the coffee bar, and he even agrees to extend the trial and let your friend create another POS for the gym, based on your code.

Things are going really well. If they continue like this, you will win the contract to replace all of the systems at the health club!

real-world format strings

The Format String

This week's interview:

Why do appearances matter?

Head First: Format String, it's a pleasure to meet you.

Format String: The pleasure is all mine.

Head First: You're not just used in Python, are you?

Format String: Oh no. I'm really used in lots of programming languages, like C, C#, and Java. You see me crop up all over the place.

Head First: Why is that?

Format String: Well, I don't like to blow my own bugle, but I am kind of useful. Everywhere you need to generate formatted text, I can make life a lot easier for you.

Head First: Can you give us some examples?

Format String: Oh sure. If you need to send data to another system, you'll probably need me. If you want to display an error message in a specific format, I'm good at that, too.

Head First: I hate to say this, it seems so rude, but isn't it possible to do everything you do with just normal string operations?

Format String: Please, I don't take offence. Yes, you can do pretty much everything I do by writing code and creating strings manually. But I don't think that's a great idea.

Head First: Why's that?

Format String: Two reasons: first, you might have to create a lot of code, and second, I'm a little more dynamic.

Head First: What do you mean?

Format String: Well, I'm just data. Lots of times, programmers prefer to use data instead of chunks of code, because it means they can store me away as configuration. So I get used a lot for things like internationalization.

Head First: Internationalization?

Format String: Yeah, say someone wants to display a message that someone has the top score. They could write the message in a file like "%d is the top score!". If they write a French version of the game, they just have to amend me to "%d est les points supérieurs!"

Head First: No code change necessary. Format String: Exactly.

Head First: String Format, thanks for your time.

iJierejflre nç

Dumb Questions

Q/ Those format strings look a little weird. How do I find out more about them?

A" A good reference book (we present our favorite in the appendix) will contain all you need to know and there's also lots of material on-line in the official Python docs.

Q/ Are there special rules for what's acceptable as a credit card number?

A" Yes, there are. But let's not get bogged down in those type of details at this stage. Concentrate on the save transaction() function and how the code interacts with it.

Why does the code generate the menu in such a complex way?

A." 'f you study the menu generation code, you will see that when you add more items and prices, the rest of the code doesn't need to change to support the new items.The menu is generated automatically.

Was this article helpful?

0 0

Post a comment