Home > Articles > Open Source > Python

📄 Contents

  1. Operators
  2. Formatting Strings—Modulus
  3. Summary
This chapter is from the book

Formatting Strings—Modulus

Although not actually modulus, the Python % operator works similarly in string formatting to interpolate variables into a formatting string. If you've programmed in C, you'll notice that % is much like C's printf(), sprintf(), and fprintf() functions.

There are two forms of %, one of which works with strings and tuples, the other with dictionaries.

StringOperand % TupleOperand 
StringOperand % DictionaryOperand 

Both return a new formatted string quickly and easily.

% Tuple String Formatting

In the StringOperand % TupleOperand form, StringOperand represents special directives within the string that help format the tuple. One such directive is %s, which sets up the format string

>>> format = "%s is my friend and %s is %s years old" 

and creates two tuples, Ross_Info and Rachael_Info.

>>> Ross_Info = ("Ross", "he", 28)
>>> Rachael_Info = ("Rachael", "she", 28)

The format string operator (%) can be used within a print statement, where you can see that every occurrence of %s is respectively replaced by the items in the tuple.

>>> print (format % Ross_Info) 
Ross is my friend and he is 28 years old 

>>> print (format % Rachael_Info) 
Rachael is my friend and she is 28 years old 

Also note that %s automatically converts the last item in the tuple to a reasonable string representation. Here's an example of how it does this using a list:

>>> bowling_scores = [190, 135, 110, 95, 195]
>>> name = "Ross"
>>> strScores = "%s's bowling scores were %s" \
...                                                 % (name, bowling_scores) 
>>> print strScores 
Ross's bowling scores were [190, 135, 110, 95, 195] 

First, we create a list variable called bowling_scores and then a string variable called name. We then use a string literal for a format string (StringOperand) and use a tuple containing name and bowling_scores.

Format Directives

Table 3–6 covers all of the format directives and provides a short example of usage for each. Note that the tuple argument containing a single item can be denoted with the % operator as item, or (item).

Table 3–6 Format Directives

Directive

Description

Interactive Session

%s

Represents a value as a string

>>> list = ["hi", 1, 1.0, 1L]

>>> "%s" % list

"['hi', 1, 1.0, 1L]"

>>> "list equals %s" % list

"list equals ['hi', 1, 1.0, 1L]"

%i

Integer

>>> "i = %i" % (5)

'i = 5'

>>> "i = %3i" % (5)

'i = 5'

%d

Decimal integer

>>> "d = %d" % 5

'd = 5'

>>> "%3d" % (3)

' 3'

%x

Hexadecimal integer

>>> "%x" % (0xff)

'ff'

>>> "%x" % (255)

'ff'

%x

Hexadecimal integer

>>> "%x" % (0xff)

'ff'

>>> "%x" % (255)

'ff'

%o

Octal integer

>>> "%o" % (255)

377

>>> "%o" % (0377)

377

%u

Unsigned integer

>>> print "%u" % -2000

2147481648

>>> print "%u" % 2000

2000

%e

Float exponent

>>> print "%e" % (30000000L)

3.000000e+007

>>> "%5.2e" % (300000000L)

'3.00e+008'

%f

Float

>>> "check = %1.2f" % (3000)

 

 

'check = 3000.00'

 

 

 

 

 

>>> "payment = $%1.2f" % 3000

 

 

'payment = $3000.00'

%g

Float exponent

>>> "%3.3g" % 100

 

 

'100.'

 

 

 

 

 

>>> "%3.3g" % 1000000000000L

 

 

'10.e11'

 

 

 

 

 

>>> "%g" % 100

 

 

'100.'

%c

ASCII character

>>> "%c" % (97)

 

 

'a'

 

 

 

 

 

>>> "%c" % 97

 

 

'a'

 

 

 

 

 

>>> "%c" % (97)

 

 

'a'


Table 3–7 shows how flags can be used with the format directives to add leading zeroes or spaces to a formatted number. They should be inserted immediately after the %.

Table 3–7 Format Directive Flags

Flag

Description

Interactive Session

#

Forces octal to have a 0 prefix; forces hex to

>>> "%#x" % 0xff

have a 0x prefix

'0xff'

>>> "%#o" % 0377

'0ff'

+

Forces a positive number to have a sign

>>> "%+d" % 100

'+100'

-

Left justification (default is right)

>>> "%-5d, %-5d" % (10,10)

'10 , 10 '

" "

Precedes a positive number with a blank space

>>> "% d,% d" % (-10, 10)

'-100,10'

0

0 padding instead of spaces

>>> "%05d" % (100,)

'00100'


Advanced Topic: Using the %d, %i, %f, and %e Directives for Formatting Numbers

The % directives format numeric types: %i works with Integer; %f and %e work with Float with and without scientific notation, respectively.

>>> "%i, %f, %e" % (1000, 1000, 1000) 
'1000, 1000.000000, 10.000000e+002' 

Notice how awkward all of those zeroes look. You can limit the length of precision and neaten up your code like this:

>>> "%i, %2.2f, %2.2e" % (1000, 1000, 1000) 
'1000, 1000.00, 10.00e+002' 

The %2.2f directive tells Python to format the number as at least two characters and to cut the precision to two characters after the decimal point. This is useful for printing floating-point numbers that represent currency.

>>> "Your monthly payments are $%1.2f" % (payment) 
'Your monthly payments are $444.43' 

All % directives have the form %min.precision(type), where min is the minimum length of the field, precision is the length of the mantissa (the numbers on the right side of the decimal point), and type is the type of directive (e, f, i, or d). If the precision field is missing, the directive can take the form %min(type), so, for example, %5d ensures that a decimal number has at least 5 fields and %20f ensures that a floating-point number has at least 20.

Let's look at the use of these directives in an interactive session.

>>> "%5d" % (100,) 
' 100' 
>>> "%20f" % (100,) 
' 100.000000' 

Here's how to truncate the float's mantissa to 2 with %20.2f.

>>> "%20.2f" % (100,) 
' 100.00' 

The padding that precedes the directive is useful for printing rows and columns of data for reporting because it makes the printed output easy to read. This can be seen in the following example (from format.py):

     # Create two rows
row1 = (100, 10000, 20000, 50000, 6000, 6, 5) 
row2 = (1.0, 2L, 5, 2000, 56, 6.0, 7) 

      # 
      # Print out the rows without formatting 
print "here is an example of the columns not lining up" 
print ´row1´ + "\n" + ´row2´ 
print 
      # 
      # Create a format string that forces the number
      # to be at least 3 characters long to the left
      # and 2 characters to the right of the decimal point
format = "(%3.2e, %3.2e, %3.2e, %3.2e, " + \ "%3.2e, %3.2e, %3.2e)" 

      # 
      # Create a string for both rows
      # using the format operator
strRow1 = format % row1 
strRow2 = format % row2 
print "here is an example of the columns" + \ 
        " lining up using \%e" 

print strRow1 + "\n" + strRow2 
print 

      # Do it again this time with the %i and %d directive 
format1 = "(%6i, %6i, %6i, %6i, %6i, %6i, %6i)" 
format2 = "(%6d, %6d, %6d, %6d, %6d, %6d, %6d)" 
strRow1 = format1 % row1 
strRow2 = format2 % row2 
print "here is an example of the columns" + \ 
        " lining up using \%i and \%d" 

print strRow1 + "\n" + strRow2 
print 

here is an example of the columns not lining up 
(100, 10000, 20000, 50000, 6000, 6, 5) 
(1.0, 2L, 5, 2000, 56, 6.0, 7) 

here is an example of the columns lining up using \%e 
(1.00e+002, 1.00e+004, 2.00e+004, 5.00e+004, 6.00e+003, 6.00e+000, 5.00e+000) 
(1.00e+000, 2.00e+000, 5.00e+000, 2.00e+003, 5.60e+001, 6.00e+000, 7.00e+000) 

here is an example of the columns lining up using \%i and \%d 
( 100, 10000, 20000, 50000, 6000, 6, 5) 
(     1,         2,         5,   2000,     56, 6, 7) 

You can see that the %3.2e directive permits a number to take up only three spaces plus the exponential whereas %6d and %6i permit at least six spaces. Note that %i and %d do the same thing that %e does. Most C programmers are familiar with %d but may not be familiar with %i, which is a recent addition to that language.

String % Dictionary

Another useful Python feature for formatting strings is StringOperand % Dictio-naryOperand. This form allows you to customize and print named fields in the string. %(Income)d formats the value referenced by the Income key. Say, for example, that you have a dictionary like the one here:

Monica = { 
                 "Occupation": "Chef",
                 "Name" : "Monica", 
                 "Dating" : "Chandler",
                 "Income" : 40000 
                  } 

With %(Income)d, this is expressed as

>>> "%(Income)d" % Monica 
'40000' 

Now let's say you have three best friends, whom you define as dictionaries named Monica, Chandler, and Ross.

Monica = { 
                 "Occupation": "Chef",
                 "Name" : "Monica", 
                 "Dating" : "Chandler", 
                 "Income" : 40000 
                 } 

Ross = 
                               { 
                "Occupation": "Scientist Museum Dude",
                "Name" : "Ross", 
                "Dating" : "Rachael", 
                "Income" : 70000 
                } 

Chandler =              { 
                "Occupation": "Buyer",
                "Name" : "Chandler", 
                "Dating" : "Monica", 
                "Income" : 65000 
                } 

To write them a form letter, you can create a format string called message that uses all of the above dictionaries' keywords.

message = "%(Name)s, %(Occupation)s, %(Dating)s," \ 
                  " %(Income)2.2f" 

Notice that %(Income)2.2f formats this with a floating-point precision of 2, which is good for currency. The output is

Chandler, Buyer, Monica, 65000.00 
Ross, Scientist Museum Dude, Rachael, 70000.00 
Monica, Chef, Chandler, 40000.00 

You can then print each dictionary using the format string operator.

print message % Chandler 
print message % Ross 
print message % Monica 

To generate your form letter and print it out to the screen, you first create a format string called dialog.

dialog = """ 
Hi %(Name)s, 

How are you doing? How is %(Dating)s? 
Are you still seeing %(Dating)s? 

How is work at the office? 
I bet it is hard being a %(Occupation)s. 
I know I could not do it. 
""" 

Then you print out each dictionary using the dialog format string with the % format string operator.

print dialog % Ross 
print dialog % Chandler 
print dialog % Monica 

The output is

Hi Ross, 

How are you doing? How is Rachael? 
Are you still seeing Rachael? 

How is work at the office? 
I bet it is hard being a Scientist Museum Dude. 
I know I could not do it. 

Hi Chandler, 
How are you doing? How is Monica? 
Are you still seeing Monica? 

How is work at the office? 
I bet it is hard being a Buyer. 
I know I could not do it. 

Hi Monica, 
How are you doing? How is Chandler? 
Are you still seeing Chandler? 

How is work at the office? 
I bet it is hard being a Chef. 
I know I could not do it. 

%(Income)d is a useful, flexible feature. You just saw how much time it can save you in writing form letters. Imagine what it can do for writing reports.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020