Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to format output in python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to format the output in python. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Foreword:

There are several ways to display the output of a program. Data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Users usually want more control over the output format rather than simply printing values separated by spaces. There are several ways to format the output.

To use formatted string text, start the string with f or F before the left or triple quotation marks.

The format () method of the string helps the user create more elegant output.

The user can complete all string processing by using string slicing and concatenation operations to create any layout the user wants. The string type has several ways to perform useful operations to populate a string to a given column width.

1 format the output using the string module operator (%)

The% operator can also be used for string formatting. It interprets the left parameter as very similar to the printf () style format in the C language string to apply to the right parameter. In Python, there is no printf () function, but the functionality of the old printf is contained in Python. To do this, the string class overloads the modular operator% to perform string formatting. Therefore, it is often referred to as the string modulus (and sometimes even modular) operator.

The string module operator (%) is still available in Python (3.x) and is widely used. Today, however, the old format has been removed from the language.

# print integer and float valueprint ("Geeks:% 2d, Portal:% 5.2f"% (1, 05.333)) # print integer valueprint ("Total students:% 3D, Boys:% 2d"% (240120)) # print octal valueprint ("% 7.3o"% (25)) # print exponential valueprint (".3e"% (356.08977))

Output:

There are two in our example: "% 2d" and "% 5.2f". The general syntax for format placeholders is:% [flags] [width] [.placeholder] type

Let's take a look at the placeholders in the example.

The first placeholder "% 2d" is used for the first component of our tuple, the integer 1. The number will print 2 characters. Because 1 contains only one digit, the output is filled with 1 leading space.

The second "% 5.2f" is the format description of a floating point number. Like other placeholders, it is introduced as the% character. This is followed by the total number of digits that the string should contain. This number includes the decimal point and all numbers, that is, before and after the decimal point.

Our floating point number 05.333 must be formatted as 5 characters. The decimal part of the number or precision is set to 2, that is, "." The following numbers. In our placeholder. Finally, the last character "f" of the placeholder stands for "float".

2 use the format method to format the output

The format () method has been added to Python (2.6). The method of formatting strings requires more manpower. The user uses {} to mark where the variable will be replaced, and can provide detailed formatting instructions, but the user also needs to provide the information to be formatted. This method allows us to connect the elements in the output through the location format. As shown in the following example:

Example 1:

# Python program showing# use of format () method # using format () methodprint ('I love {} for "{}!" '.format (' Geeks', 'Geeks')) # using format () method and referring# a position of the objectprint (' {0} and {1} '.format (' Geeks', 'Portal')) print (' {1} and {0} '.format (' Geeks', 'Portal')) # the above formatting can also be done by using f-Strings# Although This features work only with python 3.6 or above. Print (f "I love {'Geeks'} for\" {' Geeks'}!\ ") # using format () method and referring# a position of the objectprint (f" {'Geeks'} and {' Portal'} ")

Output:

The parentheses and characters (called format fields) are replaced by the object passed to the format () method. The numbers in parentheses can be used to indicate the location of the object passed to the format () method.

Example 2:

# Python program showing# a use of format () method # combining positional and keyword argumentsprint ('Number one portal is {0}, {1}, and {other}.' .format ('Geeks',' For', other = 'Geeks')) # using format () method with numberprint ("Geeks: {0Number one portal is 2d}, Portal: {1V 8.2f}". Format (12, 00.546) # Changing positional argumentprint ("Second argument: {1 Second argument 3D}, first one: {0 Second argument 7.2f}". Format (47.42,11) print ("Geeks: {aGeeks 5d}, Portal: {PRV 8.2f}". Format (a = 453, p = 59.058)

Output:

Example 3:

# Python program to# show format () is# used in dictionary tab = {'geeks': 4127,' for': 4098, 'geek': 8637678} # using format () in dictionaryprint (' Geeks: {0 [geeks]: d}; For: {0 [for]: d} '' Geeks: {0 [geek]: d} '.format (tab) data = dict (fun = "GeeksForGeeks", adj = "Portal") # using format () in dictionaryprint ("I love {fun} computer {adj}" .format (* * data))

Output:

3 use the String method to format the output

This output is formatted by using string slicing and concatenation operations. The string type has some ways to help format the output in a more exotic way. Some of the methods that help format the output are str.rjust (), str.rjust (), and str.centre ().

# Python program to# format an output using# string () method cstr = "I love geeksforgeeks" # Printing the center aligned # string with fillchrprint ("Center aligned string with fillchr:") print (cstr.center (40,'#') # Printing the left aligned # string with "-" padding print ("The left aligned string is:") print (cstr.ljust (40,'-') # Printing the right aligned string# with "-" padding print ("The right aligned string is:") print (cstr.rjust (40) '-')

Output:

This is the end of this article on "how to format output in python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report