📜  Python字符串格式() 方法

📅  最后修改于: 2022-05-13 01:55:05.424000             🧑  作者: Mango

Python字符串格式() 方法

引入了Python format()函数以更有效地处理复杂的字符串格式。内置字符串类的这种方法提供了复杂变量替换和值格式化的功能。这种新的格式化技术被认为更加优雅。 format() 方法的一般语法是字符串.format(var1, var2,…)

使用单一格式化程序

格式化程序通过将一对花括号{ }定义的一个或多个替换字段和占位符放入字符串并调用 str.format() 来工作。我们希望放入占位符并与作为参数传递给格式函数的字符串连接的值。

示例 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))


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


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


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


Python3
print("%20s" % ('geeksforgeeks', ))
print("%-20s" % ('Interngeeks', ))
print("%.5s" % ('Interngeeks', ))


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


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


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


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


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


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)


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


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)


输出 :

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

使用多个格式化程序

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

示例 2: Python String format() 方法 IndexError

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

示例3:具有多个占位符的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 geeks
Hi! My name is User and I am 19 years old
This is one two three four

使用转义序列格式化字符串

您可以在字符串中使用两个或多个特别指定的字符来格式化字符串或执行命令。这些字符称为转义序列。 Python中的转义序列以反斜杠 (\) 开头。例如,\n 是一个转义序列,其中字母 n 的常见含义被逐字转义并赋予了另一种含义——换行。

Escape sequenceDescription     Example      
\nBreaks the string into a new lineprint(‘I designed this rhyme to explain in due time\nAll I know’)
\tAdds a horizontal tabprint(‘Time is a \tvaluable thing’)
\\Prints a backslashprint(‘Watch it fly by\\as the pendulum swings’)
\’   Prints a single quoteprint(‘It doesn\’t even matter how hard you try’)
\”    Prints a double quoteprint(‘It is so\”unreal\”‘)
\amakes a sound like a bellprint(‘\a’) 

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

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

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

示例 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"))

输出 :

类型指定

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

示例:%s – 在格式化之前通过 str() 进行字符串转换

Python3

print("%20s" % ('geeksforgeeks', ))
print("%-20s" % ('Interngeeks', ))
print("%.5s" % ('Interngeeks', ))

输出:

geeksforgeeks
Interngeeks         
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有符号十进制整数(base-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))

输出:

另一个有用的类型指定

  • %u无符号十进制整数
  • %o八进制整数
  • f – 浮点显示
  • b – 二进制
  • o – 八进制
  • %x – 9 后带有小写字母的十六进制
  • %X – 9 后带有大写字母的十六进制
  • e – 指数符号

您还可以指定格式符号。唯一的变化是使用冒号 (:) 而不是 %。例如,代替 %s 使用 {:s} 代替 %d 使用 (:d}

示例 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 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:演示使用 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 :-\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

使用字典进行字符串格式化

使用字典将值解压缩到需要格式化的字符串中的占位符中。我们基本上使用**来解包这些值。在准备 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 format() 带列表

给定一个浮点值列表,任务是将所有浮点值截断为 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']