Python format

str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.

Using a Single Formatter :

Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function.

Syntax : { } .format(value)

Parameters :
(value) : Can be an integer, floating point numeric constant, string, characters or even variables.

Returntype : Returns a formatted string with the value passed as parameter in the placeholder position.

Code #1 : Simple demonstration of format().

# Python3 program to demonstarte
# the str.format() method
  
# using format option in a simple string
print ("{}, A computer science portal for geeks."
                        .format("GeeksforGeeks"))
  
# using format option for a
# value stored in a variable
str = "This article is written in {}"
print (str.format("Python"))
  
# formatting a string using a numeric constant
print ("Hello, I am {} years old !".format(18)) 

Output :

GeeksforGeeks, A computer science portal for geeks.
This article is written in Python
Hello, I am  18 years old!

Using Multiple Formatters :

Multiple pairs of curly braces can be used while formatting the string. Let’s say if another variable substitution is needed in sentence, can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders by values in order.

Syntax : { } { } .format(value1, value2)

Parameters :
(value1, value2) : Can be integers, floating point numeric constants, strings, characters and even variables. Only difference is, the number of values passed as parameters in format() method must be equal to the number of placeholders created in the string.

Errors and Exceptions :
IndexError : Occurs when string has an extra placeholder and we didn’t pass any value for it in the format() method. Python usually assigns the placeholders with default index in order like 0, 1, 2, 3…. to acces the values passed as parameters. So when it encounters a placeholder whose index doesn’t have any value passed inside as parameter, it throws IndexError.

Code #2 :

 
# Python program demonstrating Index error
  
# Number of placeholders are four but
# there are only three values passed
  
# parameters in format function.
my_string = "{}, is a {} {} science portal for {}"
  
print (my_string.format("GeeksforGeeks", "computer", "geeks"))

Output :

 
Traceback (most recent call last):
  File "/home/949ca7b5b7e26575871639f03193d1b3.py", line 2, in 
    print (my_string.format("GeeksforGeeks", "computer", "geeks"))
IndexError: tuple index out of range

 
Code #3 : Formatters with multiple place holders.

 
# Python program using multiple place 
# holders to demonstrate str.format() method 
  
# Multiple placeholders in format() function
my_string = "{}, is a {} science portal for {}"
print (my_string.format("GeeksforGeeks", "computer", "geeks"))
  
# different datatypes can be used in formatting
print ("Hi ! My name is {} and I am {} years old"
                            .format("User", 19))
  
# The values passed as parameters
# are replaced in order of their entry
print ("This is {} {} {} {}"
       .format("one", "two", "three", "four"))

Output :

GeeksforGeeks, is a computer science portal for geeks
Hi! My name is User and I am 19 years old
This is one two three four

Formatters with Positional and Keyword Arguments :

When placeholders { } are empty, Python will replace the values passed through str.format() in order.

The values that exist within the str.format() method are essentially tuple data types and each individual value contained in the tuple can be called by its index number, which starts with the index number 0. These index numbers can be passes into the curly braces that serve as the placeholders in the original string.

Syntax : {0} {1}.format(positional_argument, keyword_argument)

Parameters : (positional_argument, keyword_argument)

Positional_argument can be integers, floating point numeric constants, strings, characters and even variables.
Keyword_argument is essentially a variable storing some value, which is passed as parameter.

Code #4 :

 
# To demonstrate the use of formatters
# with positional key arguments.
  
# Positional arguments
# are placed in order
print("{0} love {1}!!".format("GeeksforGeeks",
                                    "Geeks"))
  
# Reverse the index numbers with the
# parameters of the placeholders
print("{1} love {0}!!".format("GeeksforGeeks",
                                    "Geeks"))
  
  
print("Every {} should know the use of {} {} programming and {}"
    .format("programmer", "Open", "Source", "Operating Systems"))
  
  
# Use the index numbers of the
# values to change the order that
# they appear in the string
print("Every {3} should know the use of {2} {1} programming and {0}"
        .format("programmer", "Open", "Source", "Operating Systems"))
  
  
# Keyword arguments are called
# by their keyword name
print("{gfg} is a {0} science portal for {1}"
.format("computer", "geeks", gfg ="GeeksforGeeks"))

Output :

 
GeeksforGeeks love Geeks!!
Geeks love GeeksforGeeks!!
Every programmer should know the use of Open Source programming and Operating Systems
Every Operating Systems should know the use of Source Open programming and programmer
GeeksforGeeks is a computer science portal for geeks

Type Specifying :

More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name:conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type.

s – strings
d – decimal integers (base-10)
f – floating point display
c – character
b – binary
o – octal
x – hexadecimal with lowercase letters after 9
X – hexadecimal with uppercase letters after 9
e – exponent notation

Syntax :
String {field_name:conversion} Example.format(value)

Errors and Exceptions :
ValueError : Error occurs during type conversion in this method.

Code #5 :

 
# Demonstrate ValueError while
# doing forced type-conversions
  
# When explicitly converted floating point
# values to decimal with base-10 by 'd' 
# type conversion we encounter Value-Error.
print("The temperature today is {0:d} degrees outside !"
                                        .format(35.567))
  
# Instead write this to avoid value-errors
''' print("The temperature today is {0:.0f} degrees outside !"
                                            .format(35.567))'''

Output :

Traceback (most recent call last):
  File "/home/9daca03d1c7a94e7fb5fb326dcb6d242.py", line 5, in 
    print("The temperature today is {0:d} degrees outside!".format(35.567))
ValueError: Unknown format code 'd' for object of type 'float'

 
Code #6 :


# Convert base-10 decimal integers 
# to floating point numeric constants
print ("This site is {0:f}% securely {1}!!".
                    format(100, "encrypted"))
  
# To limit the precision
print ("My average of this {0} was {1:.2f}%"
            .format("semester", 78.234876))
  
# For no decimal places
print ("My average of this {0} was {1:.0f}%"
            .format("semester", 78.234876))
  
# Convert an integer to its binary or
# with other different converted bases.
print("The {0} of 100 is {1:b}"
        .format("binary", 100))
          
print("The {0} of 100 is {1:o}"
        .format("octal", 100))

Output :

This site is 100.000000% securely encrypted!!
My average of this semester was 78.23%
My average of this semester was 78%
The binary of 100 is 1100100
The octal of 100 is 144
 

Padding Substitutions or Generating Spaces :

Code #7 :

By default strings are left-justified within the field, and numbers are right-justified. We can modify this by placing an alignment code just following the colon.

<   :  left-align text in the field
^   :  center text in the field
>   :  right-align text in the field

 

# To demonstrate spacing when 
# strings are passed as parameters
print("{0:4}, is the computer science portal for {1:8}!"
                        .format("GeeksforGeeks", "geeks"))
  
# To demonstrate spacing when numeric
# constants are passed as parameters.
print("It is {0:5} degrees outside !"
                        .format(40))
  
# To demonstrate both string and numeric
# constants passed as parameters
print("{0:4} was founded in {1:16}!"
    .format("GeeksforGeeks", 2009))
  
  
# To demonstrate aligning of spaces
print("{0:^16} was founded in {1:<4}!"
        .format("GeeksforGeeks", 2009))
  
print("{:*^20s}".format("Geeks"))

Output :

GeeksforGeeks, is the computer science portal for geeks   !
It is    40 degrees outside!
GeeksforGeeks was founded in             2009!
 GeeksforGeeks   was founded in 2009 !
*******Geeks********

Applications :

Formatters are generally used to Organize Data. Formatters can be seen in their best light when they are being used to organize a lot of data in a visual way. If we are showing databases to users, using formaters to increase field size and modify alignment can make the output more readable.

Code #8 : To demonstrate organization of large data

 
# which prints out i, i ^ 2, i ^ 3,
#  i ^ 4 in the given range
  
# Function prints out values
# in an unorganized manner
def unorganized(a, b):
    for i in range (a, b):
        print ( i, i**2, i**3, i**4 )
  
# Function prints the organized set of values
def organized(a, b):
    for i in range (a, b):
  
        # Using formatters to give 6 
        # spaces to each set of values
        print("{:6d} {:6d} {:6d} {:6d}"
        .format(i, i ** 2, i ** 3, i ** 4))
  
# Driver Code
n1 = int(input("Enter lower range :- "))
n2 = int(input("Enter upper range :- "))
  
print("------Before Using Formatters-------")
  
# Calling function without formatters
unorganized(n1, n2)
  
print()
print("-------After Using Formatters---------")
print()
  
# Calling function that contain
# formatters to organize the data
organized(n1, n2)

Output :

Enter lower range :-
3
Enter upper range :-
10
------Before Using Formatters-------
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401
8 64 512 4096
9 81 729 6561

-------After Using Formatters---------

     3      9     27     81
     4     16     64    256
     5     25    125    625
     6     36    216   1296
     7     49    343   2401
     8     64    512   4096
     9     81    729   6561


Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

实例

>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'

也可以设置参数:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com")) # 通过字典设置参数 site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['菜鸟教程', 'www.runoob.com'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

输出结果为:

网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com

也可以向 str.format() 传入对象:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('value 为: {0.value}'.format(my_value)) # "0" 是可选的

输出结果为:

value 为: 6

数字格式化

下表展示了 str.format() 格式化数字的多种方法:

>>> print("{:.2f}".format(3.1415926));
3.14
数字格式输出描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:>10d}         13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d}     13 中间对齐 (宽度为10)
11
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
进制

^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

+ 表示在正数前显示 +,负数前显示 -;  (空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

此外我们可以使用大括号 {} 来转义大括号,如下实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- print ("{} 对应的位置是 {{0}}".format("runoob"))

输出结果为:

runoob 对应的位置是 {0}



from https://www.geeksforgeeks.org/python-format-function/ and https://www.runoob.com/python/att-string-format.html
原文地址:https://www.cnblogs.com/xxxsans/p/13631447.html