当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python format()用法及代码示例


str.format()是Python3中的一种字符串格式化方法,它允许多次替换和值格式化。此方法使我们可以通过位置格式将字符串中的元素连接起来。

使用单个格式化程序:

格式化程序的工作原理是,将由一对大括号{}定义的一个或多个替换字段和占位符放入字符串中,然后调用str.format()。我们希望放入占位符的值,并将其作为参数传递给格式函数的字符串连接起来。

用法: { } .format(value)

参数:
(value):可以是整数,浮点数字常量,字符串,字符甚至变量。

Returntype:返回一个格式化的字符串,该字符串的值在占位符位置作为参数传递。

代码1: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)) 

输出:

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

使用多个格式化程序:

格式化字符串时,可以使用多对花括号。假设如果句子中需要另一个变量替换,可以通过添加第二对花括号并将第二个值传递给方法来完成。 Python将按顺序将占位符替换为值。

用法: { } { } .format(value1, value2)

参数:
(value1, value2):可以是整数,浮点数字常量,字符串,字符甚至变量。唯一的区别是,在format()方法中作为参数传递的值的数量必须等于在字符串中创建的占位符的数量。

错误和异常:
IndexError:当string有一个额外的占位符并且我们没有在format()方法中为其传递任何值时发生。 Python通常会按默认索引为占位符分配顺序,例如0、1、2、3…。访问作为参数传递的值。因此,当遇到占位符,该占位符的索引中没有任何值作为参数传递时,它将引发IndexError。

代码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"))

输出:


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


代码3:具有多个占位符的格式化程序。

# 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"))

输出:

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

带有位置和关键字参数的格式化程序:

当占位符{}为空时,Python将按顺序替换通过str.format()传递的值。

str.format()方法中存在的值本质上是元组数据类型,并且元组中包含的每个单独值都可以通过其索引号(从索引号0开始)进行调用。这些索引号可以传递到花括号中,充当原始字符串中的占位符。

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

参数:(positional_argument,keyword_argument)

Positional_argument可以是整数,浮点数字常量,字符串,字符甚至变量。
Keyword_argument本质上是一个存储一些值的变量,该值作为参数传递。

代码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"))

输出:


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

类型指定:

语法的花括号中可以包含更多参数。使用格式代码语法{field_name:conversion},其中field_name指定str.format()方法的参数的索引号,而转换是 index 据类型的转换代码。

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

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

错误和异常:
ValueError:使用此方法进行类型转换时发生错误。

代码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))'''

输出:

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'


代码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))

输出:

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


填充替换或生成空间:

代码7:

默认情况下,字段中的字符串为left-justified,数字为right-justified。我们可以通过在冒号后面放置一个对齐代码来修改它。

<  : 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"))

输出:

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

应用范围:

格式化程序通常用于组织数据。当格式化程序用于以可视方式组织大量数据时,可以以最佳状态看到它们。如果我们向用户显示数据库,则使用格式化程序增加字段大小并修改对齐方式可以使输出更具可读性。

代码8:演示大数据的组织

# 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:-\n")) 
n2 = int(input("Enter upper range:-\n")) 
  
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)

输出:

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



相关用法


注:本文由纯净天空筛选整理自retr0大神的英文原创作品 Python | format() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。