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


Python String format()用法及代碼示例


在 Python 3.0 中,引入了 format() 方法以更有效地處理複雜的字符串格式。 內置 字符串類的這個方法提供了複雜變量替換和值格式化的函數。這種新的格式化技術被認為更優雅。 format() 方法的一般語法是 string.format(var1, var2,...)

使用單個格式化程序:

格式化程序通過將一個或多個由一對花括號 { } 定義的替換字段和占位符放入字符串並調用 str.format() 來工作。我們希望放入占位符並與作為參數傳遞給格式函數的字符串連接的值。

用法: { } .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. 
 

代碼1:format() 的簡單演示。



Python3


# Python3 program to demonstrate
# 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): 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 access 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. 
 

代碼2:

Python3


# 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:具有多個占位符的格式化程序。

Python3


# 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 中的轉義序列以反斜杠 (\) 開頭。例如,\n 是一個轉義序列,其中字母 n 的常見含義被逐字轉義並賦予替代含義 - 換行。

轉義序列描述示例
\ n將字符串分成新行print('我設計這首韻文是為了及時解釋\n我所知道的')
\t添加水平標簽打印('時間是一個\t有價值的東西')
\\打印反斜杠打印('看著它飛過\\當鍾擺擺動')
\’打印單引號print('即使你再努力也沒關係')
\”打印雙引號打印('它是如此\“不真實\”')
\一種發出像鍾聲的聲音打印(‘\a’)

帶有位置和關鍵字參數的格式化程序:

當占位符 { } 為空時,Python 將按順序替換通過 str.format() 傳遞的值。 str.format() 方法中存在的值本質上是元組數據類型,元組中包含的每個單獨值都可以通過其索引號調用, 以索引號 0 開頭。這些索引號可以傳遞到大括號中,用作原始字符串中的占位符。

用法: {0} {1}.format(positional_argument, keyword_argument)
參數: (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.

代碼#4:

Python3


# 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()方法的參數索引號,conversion指的是數據類型的轉換代碼。

%s - string conversion via str() prior to formatting

example: 

1)print(“%20s” % (‘geeksforgeeks’, ))



output- geeksforgeeks

2)print(“%-20s” % (‘Interngeeks’, ))

output- Interngeeks

3)print(“%.5s” % (‘Interngeeks’, ))

output- Inter

%c- character 

example: 

type=’bug’ 

result=’troubling’  

print(‘I wondered why the program was %s me. Then it dawned on me it was a %s .’ %(result, type ))

output-I wondered why the program was me troubling me. Then it dawned on me it was a bug.

%i- signed decimal integer

%d- signed decimal integer(base-10) 

example-

match=12000

site=’amazon’

print(“%s is so useful. I tried to look up mobile and they had a nice one that cost %d rupees.” % (site, match))

output- amazon is so useful. I tried to look up mobiles and they had a nice one that cost 12000 rupees”)

%u unsigned decimal integer 
%o octal integer 
f - floating point display 
b - binary 
o - octal 
%x - hexadecimal with lowercase letters after 9 
%X- hexadecimal with uppercase letters after 9 
e - exponent notation

You can also specify formatting symbols. Only change is using colon (:) instead of %. For example, instead of %s use {:s} and instead of %d use (:d}



用法: 
String {field_name:conversion} Example.format(value)
Errors and Exceptions: 
ValueError:Error occurs during type conversion in this method. 

代碼#5:

Python3


# 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:

Python3


# 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-align text in the field
^  : center text in the field
>  : right-align text in the field

Python3


# 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:演示大數據的組織

Python3


# 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 contains
# 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

使用字典進行字符串格式化:

代碼#9:使用字典將值解包到需要格式化的字符串中的占位符中。我們本質上使用 ** 來解包值。在準備 SQL 查詢時,此方法可用於字符串替換。

Python3


introduction = 'My name is {first_name} {middle_name} {last_name} AKA the {aka}.'
full_name = {
    'first_name':'Tony',
    'middle_name':'Howard',
      'last_name':'Stark',
      'aka':'Iron Man',
}
  
# Notice the use of "**" operator to unpack the values.
print(introduction.format(**full_name))
輸出
My name is Tony Howard Stark AKA the Iron Man.




相關用法


注:本文由純淨天空篩選整理自retr0大神的英文原創作品 Python String format() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。