當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。