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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。