本文共 7816 字,大约阅读时间需要 26 分钟。
Python String format() function is used to create a formatted string from the template string and the supplied values.
Python String format()函数用于根据模板字符串和提供的值创建格式化的字符串。
Python String format() function syntax is:
Python字符串format()函数语法为:
str.format(*args, **kwargs)
{}
as delimiter. 模板字符串可以是字符串文字,也可以包含使用{}
作为分隔符的替换字段。 Let’s look at some examples of using format() function.
让我们看一些使用format()函数的示例。
print("My Name is {0}".format("Pankaj"))print("I like {0} and {1}".format("Java", "Python"))# same as aboveprint("I like {} and {}".format("Java", "Python"))# index can be in any orderprint("I like {1} and {0}".format("Java", "Python"))
Output:
输出:
My Name is PankajI like Java and PythonI like Java and PythonI like Python and Java
# unpacking from sequencest = ("Java", "Python")print("I like {1} and {0}".format(*t))l = ["Java", "Python"]print("I like {} and {}".format(*t))
Output:
输出:
I like Python and JavaI like Java and Python
print("{name} is the {job} of {company}".format(name="Pankaj", job="CEO", company="JournalDev"))
Output: Pankaj is the CEO of JournalDev
输出: Pankaj is the CEO of JournalDev
We can use dictionary in format() function argument for keyword based field replacements.
我们可以在format()函数参数中使用基于字典的关键字替换字段。
d = {"name": "Pankaj", "job": "CEO", "company": "JournalDev"}print("{company} {job} is {name}".format(**d))
Output: JournalDev CEO is Pankaj
输出: JournalDev CEO is Pankaj
We can pass an object in format() method and use the dot operator to access its attributes for field replacement.
我们可以通过format()方法传递一个对象,并使用点运算符访问其属性以进行字段替换。
class Data: id = 0 name = '' def __init__(self, i, n): self.id = i self.name = ndt = Data(1, 'Test')print("{obj_name} id is {obj.id} and name is {obj.name}".format(obj_name="Data", obj=dt))
Output: Data id is 1 and name is Test
输出: Data id is 1 and name is Test
We can create a string of specified length using format() method. By default, it will be left aligned and white spaces will be used for padding. However, we can specify character to use for padding and alignment for source string.
我们可以使用format()方法创建一个指定长度的字符串。 默认情况下,它将保持左对齐,空白将用于填充。 但是,我们可以指定用于填充和对齐源字符串的字符。
>>> "{:^30}".format("data center aligned")' data center aligned '>>> "{:30}".format("data without align")'data without align '>>> "{:<30}".format("data left aligned")'data left aligned '>>> "{:>30}".format("data right aligned")' data right aligned'>>> "{:^30}".format("data center aligned")' data center aligned '>>> "{:|^30}".format("data with fill character")'|||data with fill character|||'
I am using Python console for this example so that you can see the white spaces padding in the string. If we use print() function here, the quotes around the string will be not shown and string length will not be clear.
我在此示例中使用的是Python控制台,以便您可以在字符串中看到空白填充。 如果我们在此处使用print()函数,则不会显示字符串周围的引号,并且字符串长度也不清楚。
There are many formatting options for numbers, let's look at some of them.
数字有许多格式设置选项,让我们看一下其中的一些。
print('{:+f}; {:+f}'.format(1.23, -1.23))print('{: f}; {: f}'.format(1.23, -1.23))print('{:-f}; {:-f}'.format(1.23, -1.23))
Output:
输出:
+1.230000; -1.230000 1.230000; -1.2300001.230000; -1.230000
Notice that in the second statement, whitespace is being used as the prefix for the number. For negative numbers, minus (-) sign is used always.
请注意,在第二条语句中,空格被用作数字的前缀。 对于负数,始终使用负号(-)。
We can easily convert an int to different bases, such as hexadecimal, octal, binary etc. We can also specify whether the formatted string will contain the prefixes for the base or not.
我们可以轻松地将int转换为不同的基数,例如十六进制,八进制,二进制等。我们还可以指定格式化的字符串是否包含基数的前缀。
print("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(28))print("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(0x1c))print("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(28))
Output:
输出:
int: 28; hex: 1c; oct: 34; bin: 11100int: 28; hex: 1c; oct: 34; bin: 11100int: 28; hex: 0x1c; oct: 0o34; bin: 0b11100
complex_number = 4 + 2jprint("Real: {0.real}, Imaginary: {0.imag}".format(complex_number))
Output: Real: 4.0, Imaginary: 2.0
输出: Real: 4.0, Imaginary: 2.0
It's just like accessing attributes of an object.
就像访问对象的属性一样。
print('{:,}'.format(1234567890))
Output: 1,234,567,890
输出: 1,234,567,890
print('Percentage: {:.3%}'.format(19 / 28))print('{0:7.2f}'.format(2.344))print('{0:10.2f}'.format(22222.346))
Output:
输出:
Percentage: 67.857% 2.34 22222.35
Note that rounding after decimal places are done as per the default rounding rules. Also, the padding is done in front of the number.
请注意,小数点后的舍入是根据默认舍入规则进行的。 另外,在数字前面进行填充。
We can call str() and repr() functions easily for an object using !s
and !r
respectively.
我们可以分别使用!s
和!r
轻松地为对象调用str()和repr()函数。
print("With Quotes: {0!r}, Without Quotes: {0!s}".format("Data"))class Test: def __str__(self): return 'test str' def __repr__(self): return 'test repr'print("Test Representation: {0!r}, Test String Representation: {0!s}".format(Test()))
Output:
输出:
With Quotes: 'Data', Without Quotes: DataTest Representation: test repr, Test String Representation: test str
Python String format() method is very powerful in creating a string from different kinds of input sources and apply the formatting rules. It's far better than earlier % based formatting and template strings. However, if you are using Python 3.6+, you should also look at f-string formatting (PEP 498 -- Literal String Interpolation).
Python String format()方法在从不同类型的输入源创建字符串并应用格式设置规则方面非常强大。 它比以前的基于%的格式和模板字符串要好得多。 但是,如果您使用的是Python 3.6+,则还应该查看f字符串格式(PEP 498-文字字符串插值)。
Reference:
参考:
翻译自:
转载地址:http://qamzd.baihongyu.com/