📜  Python 字符串格式化 - Python (1)

📅  最后修改于: 2023-12-03 15:04:16.226000             🧑  作者: Mango

Python 字符串格式化 - Python

Python字符串格式化是将一个字符串模板和一组数据翻译成新的字符串的过程。字符串格式化在Python中是一个重要的操作, 无论是常规数据操作还是web编程。在Python中,字符串格式化主要有三种方法:使用百分号、使用format()方法和使用f-strings。在本篇文章中,我们将详细讨论这三种方法。

字符串格式化方法1: 使用百分号

使用百分号是Python 2.0之前的字符串格式化方法。在此方法中,我们使用占位符将变量值插入到一个字符串中。下面是一个基本的示例:

name = 'Tom'
age = 20
print('My name is %s and I am %d years old.' % (name, age))

输出结果:

My name is Tom and I am 20 years old.

在此示例中,我们使用了%s和%d两个占位符。%s占位符用于字符串,而%d占位符用于数值类型。

除了%s和%d占位符之外,还有其他常用的占位符:

| 占位符 | 数据类型 | | ------ | ------ | | %s | 字符串 | | %d | 整数 | | %f | 浮点数 | | %e | 科学计数法 | | %x | 十六进制整数 |

在此方法中,我们可以使用一个百分号来表示一个百分号。下面是一个示例:

rate = 0.25
print('The value of rate is %.2f%%.' % (rate * 100))

输出结果:

The value of rate is 25.00%.
字符串格式化方法2: 使用format()方法

format()方法是Python 2.6和Python 3之后的新功能。使用此方法,我们可以在一个大括号{}中使用占位符,然后使用format()方法来传递数据。下面是一个示例:

name = 'Tom'
age = 20
print('My name is {} and I am {} years old.'.format(name, age))

输出结果:

My name is Tom and I am 20 years old.

类似于使用百分号格式化方法,我们可以使用format()方法来使用不同的占位符:

name = 'Tom'
age = 20
print('My name is {0} and I am {1:d} years old.'.format(name, age))

输出结果:

My name is Tom and I am 20 years old.

在此示例中,我们在第2个大括号中指定了一个:d,表示整数类型。

格式化方法还具有更多功能,例如指定变量宽度、左对齐、右对齐等。

name = 'Tom'
age = 20
print('My name is {0:10} and I am {1:5d} years old.'.format(name, age))
print('My name is {0:<10} and I am {1:>5d} years old.'.format(name, age))

输出结果:

My name is Tom        and I am    20 years old.
My name is Tom        and I am    20 years old.

在此示例中,我们使用了:<和:>来指定字符串的对齐方式。

字符串格式化方法3: 使用f-strings

f-strings是Python 3.6之后的新功能。使用此方法,我们可以使用f-strings来构建格式化字符串,然后将数据放入字符串中。下面是一个示例:

name = 'Tom'
age = 20
print(f'My name is {name} and I am {age} years old.')

输出结果:

My name is Tom and I am 20 years old.

在此示例中,我们在字符串前面添加了一个f,然后在字符串中使用大括号{}来表示变量。使用f-strings时,我们可以像使用format()方法一样使用不同的占位符。

name = 'Tom'
age = 20
print(f'My name is {name} and I am {age:d} years old.')

输出结果:

My name is Tom and I am 20 years old.

在此示例中,我们在第二个大括号中指定了一个:d,表示整数类型。

总结

在Python字符串格式化中,我们学习了三种不同的方法:使用百分号、使用format()方法和使用f-strings。使用百分号是Python 2.0之前的方法,而使用format()方法和f-strings是Python 2.6和Python 3之后的方法。每种方法都有各自的优劣之处,我们可以根据具体情况选择不同的方法来格式化字符串。