Python format()函数 为了更有效地处理复杂的字符串格式,引入了。这个内置string类的方法提供了复杂变量替换和值格式化的功能。这种新的格式化技术被认为更加优雅。format()方法的一般语法是string。格式(var1,var2,…)
使用单个格式化程序
格式化程序通过放入一个或多个替换字段和由一对大括号定义的占位符来工作 { } 并调用str.format()。我们希望放入占位符并与作为参数传递到format函数中的字符串连接的值。
语法: { } .格式(值)
参数: (价值): 可以是整数、浮点数字常量、字符串、字符甚至变量。 返回类型: 返回一个格式化字符串,其值作为参数传递到占位符位置。
例1: 格式的简单演示()
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 PythonHello, I am 18 years old!
使用多个格式化程序
格式化字符串时,可以使用多对大括号。假设句子中需要另一个变量替换,可以通过添加第二对大括号并向方法中传递第二个值来完成。Python将用中的值替换占位符 顺序
语法: { } { } .格式(值1、值2)
参数: (价值1,价值2): 可以是整数、浮点数字常量、字符串、字符甚至变量。唯一的区别是,format()方法中作为参数传递的值的数量必须等于字符串中创建的占位符的数量。
错误和例外:
索引器: 当字符串有一个额外的占位符,并且我们没有在format()方法中为其传递任何值时发生。Python通常按如下顺序分配带有默认索引的占位符 0, 1, 2, 3…. 访问作为参数传递的值。因此,当它遇到一个占位符,而该占位符的索引中没有任何作为参数传递的值时,它抛出indexer。
例2: Python字符串格式()方法索引器
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" )) |
输出:
IndexError: tuple index out of range
实例 三: 带有多个占位符的Python字符串格式()
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 geeksHi! My name is User and I am 19 years oldThis is one two three four
使用转义序列格式化字符串
可以在字符串中使用两个或多个特殊指定的字符来格式化字符串或执行命令。这些字符被称为转义序列。Python中的转义序列以反斜杠()开头。例如是一个转义序列,在这个序列中,字母n的共同含义被逐字转义,并被赋予另一种含义——一个新行。
逃逸序列 | 描述 | 实例 |
---|---|---|
把绳子折成新行 | 我设计这首诗是为了适时解释我只知道’) | |
添加水平选项卡 | 打印(“时间是有价值的东西”) | |
\ | 打印反斜杠 | 打印(“看着它飞过\随着钟摆摆动”) |
’ | 打印一个报价 | 打印(‘你怎么努力都不重要’) |
” | 打印双引号 | 打印(‘太“不真实了’) |
A. | 发出像铃一样的声音 | 打印(’a’) |
具有位置参数和关键字参数的格式化程序
当占位符 { } 如果为空,Python将按顺序替换通过str.format()传递的值。
str.format()方法中存在的值本质上是 元组数据类型 元组中包含的每个值都可以通过其索引号调用,该索引号从索引号0开始。这些索引号可以传递到大括号中,大括号用作原始字符串中的占位符。
语法: {0} {1}.格式(位置参数、关键字参数)
参数: (位置参数、关键字参数) 位置参数 可以是整数、浮点数字常量、字符串、字符甚至变量。 关键字_参数 本质上是一个存储某些值的变量,该值作为参数传递。
例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" )) |
输出:
极客喜欢极客!!
极客喜欢极客!!
每个程序员都应该知道开源编程和操作系统的使用
每个操作系统都应该知道开源编程和程序员的用法
GeekSforgeks是一个面向极客的计算机科学门户网站
类型指定
在我们语法的大括号中可以包含更多参数。使用格式代码语法 {字段名称: 转换} 哪里 字段名称 指定str.format()方法的参数的索引号,conversion指的是数据类型的转换代码。
示例:%s –格式化前通过str()进行字符串转换
Python3
print ( "%20s" % ( 'geeksforgeeks' , )) print ( "%-20s" % ( 'Interngeeks' , )) print ( "%.5s" % ( 'Interngeeks' , )) |
输出:
geeksforgeeksInterngeeks Inter
示例:%c –性格
Python3
type = 'bug' result = 'troubling' print ('I wondered why the program was % s me. Then it dawned on me it was a % s .' % (result, type )) |
输出:
我想知道为什么这个项目让我烦恼。然后我意识到这是一只虫子。
示例:%i 带符号十进制整数和 %d 有符号十进制整数(以10为基数)
Python3
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)) |
输出:
亚马逊非常有用。我试着查找手机,他们有一个很好的手机,价格为12000卢比
另一个有用的类型是
- %u 无符号十进制整数
- %o 八进制整数
- F –浮点显示
- B –二进制
- o –八进制
- %x –十六进制,9后加小写字母
- %X –十六进制,大写字母在9之后
- E –指数表示法
还可以指定格式符号。唯一的变化是使用冒号(:)而不是%。例如,代替%s使用{:s},代替%d使用(:d}
语法: 字符串{field_name:conversion}示例。格式(值) 错误和例外: ValueError: 在此方法中进行类型转换时出错。
例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))''' |
输出:
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 1100100The 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: 使用format()演示大数据的组织
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 :-" )) 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 contains # formatters to organize the data organized(n1, n2) |
输出:
Enter lower range :-3Enter upper range :-10------Before Using Formatters-------3 9 27 814 16 64 2565 25 125 6256 36 216 12967 49 343 24018 64 512 40969 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
使用字典设置字符串格式
使用字典将值解压到需要格式化的字符串中的占位符中。我们基本上使用 ** 来解包这些值。此方法在准备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.
带列表的Python格式()
给定一个浮点值列表,任务是将所有浮点值截断为2位十进制数字。让我们看看完成这项任务的不同方法。
Python3
# Python code to truncate float # values to 2 decimal digits. # List initialization Input = [ 100.7689454 , 17.232999 , 60.98867 , 300.83748789 ] # Using format Output = [ '{:.2f}' . format (elem) for elem in Input ] # Print output print (Output) |
输出:
['100.77', '17.23', '60.99', '300.84']