📜  如何在Python中使用字符串格式化程序?

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

如何在Python中使用字符串格式化程序?

作为程序结果显示的输出应进行组织,以便可读和可理解。可以使用下面列出的各种方式打印和格式化输出字符串。

  1. 使用打印()
  2. 使用格式说明符。
  3. 使用format()方法。
  4. 使用格式化字符串字面量(f-string)

本文涵盖了上面给出的前三种方法。

使用打印()

print()函数用于显示在Python中执行的进程的任何消息或输出。此函数可用于打印字符串或任何对象。但是,在打印非字符串类型的对象之前,print() 会将其转换为字符串。可以使用此方法本身的参数或使用本文中介绍的其余方法来格式化字符串。此函数的分隔符参数 ( sep ) 可以帮助在正在打印的每个元素之间显示所需的符号。

示例:在按升序排列列表的同时打印每次迭代中的交换

Python3
# initialize the list
li = [1, 4, 93, 2, 3, 5]
  
print("Swaps :")
  
# loop for arranging
for i in range(0, len(li)):
  
    for j in range(i+1, len(li)):
  
        # swap if i>j
        if li[i] > li[j]:
            temp = li[j]
            li[j] = li[i]
            li[i] = temp
  
            # print swapped elements
            print(li[i], li[j], sep="<--->")
  
print("Output :", li)


Python3
# string
st = "This is a string"
print("String is %s" % (st))
  
# single character
ch = 'a'
print("Single character is %c" % (ch))
  
# integer
num = 45
print("The number is %d" % (num))
  
# float without specified precision
float1 = 34.521094
print("The float is %f" % (float1))
  
# float with precision
float2 = 7334.34819560
print("The float with precision is %.3f" % (float2))
  
# multiple specifiers in print()
# Hexa decimal representation
print("The hexadecimal form of %d is %x" % (num, num))
  
# octal representation
print("The octal form of %d is %o" % (num, num))
  
# exponential form
print("The exponential form of %f is %e" % (float1, float1))
  
# exponential form with appended space
print("The exponential form of %f is %10.3g" % (float2, float2))
  
# exponent less than -4 with appended space
float3 = 3.14
print("The exponential form of %.2f is %10.3g" % (float3, float3))


Python3
# complex number
c = complex(5+9j)
  
# without format() method
print("Without format() - Imaginary :", str(c.imag), " Real :", str(c.real))
  
# with format() method
print("With format() - Imaginary : {} Real : {}".format(c.imag, c.real))


Python3
# class for holding person's details
class person:
  
    # constructor
    def __init__(self, name, age, des):
        self.name = name
        self.age = age
        self.des = des
  
    # overriding format()
    def __format__(self, f):
  
        if f == 'name':
            return "I am "+self.name
  
        if f == 'age':
            return "My age is "+str(self.age)
  
        if f == 'des':
            return "I work as "+self.des
  
  
p = person('nisha', 23, 'manager')
print("{:name}, {:age}".format(p, p))
print("{:des}".format(p))


Python3
name = "Rinku"
age = 20
  
print(f"Hi! my name is {name} and my age is {age}")


Python3
a = 5
b = 6
  
print(F"Addition : {a+b}")
print(F"Subtraction : {a-b}")
print(F"Multiplication : {a*b}")
print(F"Division without roundoff : {a/b}")
print(F"Division with roundoff : {round(a/b,3)}")


Python3
# f function to evaluate expression
def exp_eval(a, b):
    ans = (a*a)+(3*(b*b))+(a*b)
    return ans
  
  
# values to be evaluated
a = 2
b = 4
  
# formatting
print(f"The expression a**2+3b**2+(a*b) = {exp_eval(a,b)}")


输出
Swaps :
2<--->4
4<--->93
3<--->4
4<--->93
5<--->93
Output : [1, 2, 3, 4, 5, 93]

使用格式说明符

格式说明符是我们在 C 编程等语言中使用的格式说明符。 Python没有 C 中的 printf(),但此处提供了相同的功能。模运算符('%') 被字符串类重载以格式化输出。 %运算符格式化包含在元组中的变量集。如果链接了多个格式说明符,则第一个说明符作用于元组中的第 0元素,第二个作用于元组中的一个元素,依此类推。下表给出了格式说明符。

Format specifier

                             Description                                        

%s

Specifies the String

%c

Specifies a single character

%d

Specifies the integer

%f

Specifies the float. Any number of digits can be present after decimal point

%.f

Specifies the float. denotes the number of space to append before printing the number.

  denotes the number of digits to be present after the decimal point.

%x / %X

Specifies the hexadecimal representation of the value

%o

Specifies the octal representation of a value

%e / %E

Specifies the floating numbers in exponential format

%g / %G

Similar to %e/%E. Specifies the exponential format only if the exponent is greater than -4

例子:

蟒蛇3

# string
st = "This is a string"
print("String is %s" % (st))
  
# single character
ch = 'a'
print("Single character is %c" % (ch))
  
# integer
num = 45
print("The number is %d" % (num))
  
# float without specified precision
float1 = 34.521094
print("The float is %f" % (float1))
  
# float with precision
float2 = 7334.34819560
print("The float with precision is %.3f" % (float2))
  
# multiple specifiers in print()
# Hexa decimal representation
print("The hexadecimal form of %d is %x" % (num, num))
  
# octal representation
print("The octal form of %d is %o" % (num, num))
  
# exponential form
print("The exponential form of %f is %e" % (float1, float1))
  
# exponential form with appended space
print("The exponential form of %f is %10.3g" % (float2, float2))
  
# exponent less than -4 with appended space
float3 = 3.14
print("The exponential form of %.2f is %10.3g" % (float3, float3))
输出
String is This is a string
Single character is a
The number is 45
The float is 34.521094
The float with precision is 7334.348
The hexadecimal form of 45 is 2d
The octal form of 45 is 55
The exponential form of 34.521094 is 3.452109e+01
The exponential form of 7334.348196 is   7.33e+03
The exponential form of 3.14 is       3.14

使用 format() 方法

format() 是字符串类中的方法之一,它允许用要格式化的值替换占位符。

参数分为两类,即:

  • Positional –要格式化的对象的索引将写入占位符内。
  • 关键字参数为key=value类型。键将写入占位符内。

也可以使用此方法执行特定于类型的格式化。日期时间对象、复数也可以使用此方法进行格式化。

例子:

蟒蛇3

# complex number
c = complex(5+9j)
  
# without format() method
print("Without format() - Imaginary :", str(c.imag), " Real :", str(c.real))
  
# with format() method
print("With format() - Imaginary : {} Real : {}".format(c.imag, c.real))
输出
Without format() - Imaginary : 9.0  Real : 5.0
With format() - Imaginary : 9.0 Real : 5.0

format() 方法可以在类和 dunder 方法的帮助下被覆盖。

蟒蛇3

# class for holding person's details
class person:
  
    # constructor
    def __init__(self, name, age, des):
        self.name = name
        self.age = age
        self.des = des
  
    # overriding format()
    def __format__(self, f):
  
        if f == 'name':
            return "I am "+self.name
  
        if f == 'age':
            return "My age is "+str(self.age)
  
        if f == 'des':
            return "I work as "+self.des
  
  
p = person('nisha', 23, 'manager')
print("{:name}, {:age}".format(p, p))
print("{:des}".format(p))
输出
I am nisha, My age is 23
I work as manager

使用 f 字符串

这个方法是在Python 3.6 版本中引入的。这比使用格式说明符或 format() 方法容易得多。 f 字符串是在运行时计算并由__format__() 方法格式化的表达式。要使用 f-string 格式化字符串,格式化表达式必须写在引号中,前面有'f'/'F'

示例1

姓名和年龄是变量。通过将变量放在适当的占位符中,可以在 f-string 的帮助下格式化和打印它们。占位符只是文本中的花括号。

蟒蛇3

name = "Rinku"
age = 20
  
print(f"Hi! my name is {name} and my age is {age}")
输出
Hi! my name is Rinku and my age is 20

示例 2:

还可以使用此 f-string 方法评估和显示表达式。

蟒蛇3

a = 5
b = 6
  
print(F"Addition : {a+b}")
print(F"Subtraction : {a-b}")
print(F"Multiplication : {a*b}")
print(F"Division without roundoff : {a/b}")
print(F"Division with roundoff : {round(a/b,3)}")
输出
Addition : 11
Subtraction : -1
Multiplication : 30
Division without roundoff : 0.8333333333333334
Division with roundoff : 0.833

示例 3:

甚至可以从 f 字符串占位符调用函数。在占位符中定义并调用了用于计算表达式a 2 + 3b 2 + ab的函数。

蟒蛇3

# f function to evaluate expression
def exp_eval(a, b):
    ans = (a*a)+(3*(b*b))+(a*b)
    return ans
  
  
# values to be evaluated
a = 2
b = 4
  
# formatting
print(f"The expression a**2+3b**2+(a*b) = {exp_eval(a,b)}")
输出
The expression a**2+3b**2+(a*b) = 60