博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python字符串格式()
阅读量:2531 次
发布时间:2019-05-11

本文共 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字符串格式() (Python String format())

Python String format() function syntax is:

Python字符串format()函数语法为:

str.format(*args, **kwargs)
  • The template string can be a string literal or it can contains replacement fields using {} as delimiter.

    模板字符串可以是字符串文字,也可以包含使用{}作为分隔符的替换字段。
  • The replacement field can be a numeric index of the arguments provided, or they can be keyword based arguments.

    替换字段可以是所提供参数的数字索引,也可以是基于关键字的参数。
  • If the replacement fields have no index or keyword value, then they are replaced based on index and in order i.e. 0,1,…,n.

    如果替换字段没有索引或关键字值,则根据索引和顺序(即0,1,…,n)进行替换。
  • We can provide sequences such as and as argument for index based replacement.

    我们可以提供诸如和序列作为基于索引的替换的参数。
  • We can provide as argument for keyword based replacements.

    我们可以提供作为基于关键字的替换的参数。
  • The format function argument can be an object too, we can access its attributes using dot operator for replacement field.

    format函数参数也可以是一个对象,我们可以使用点运算符替换字段来访问其属性。
  • We can create a specified length string using format() function with the string literal right, left or center aligned. We can also specify the character to use for padding, default is white space.

    我们可以使用format()函数创建一个指定长度的字符串,该字符串的字面量为右,左或中心对齐。 我们还可以指定用于填充的字符,默认为空白。
  • String format() function provides a lot of features to format numbers. For example, base conversion from decimal to octal, hex etc. We can also perform percentage, padding etc.

    字符串format()函数提供了许多格式化数字的功能。 例如,从十进制到八进制,十六进制等的基本转换。我们还可以执行百分比,填充等。
  • There are shortcut ways to call __str__() and __repr__() functions on an argument using !s and !r.

    有一些快捷方式可以使用!s!r在参数上调用__str __()和__repr __()函数。

Python字符串format()示例 (Python String format() Examples)

Let’s look at some examples of using format() function.

让我们看一些使用format()函数的示例。

基于简单索引的格式 (Simple Index Based Formatting)

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

序列作为format()参数 (Sequences as format() argument)

# 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

格式为()的关键字参数 (Keyword arguments in format())

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

字典作为format()参数 (Dictionary as format() argument)

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

访问对象属性以进行字段替换 (Accessing Object attributes for field replacement)

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

带填充和对齐的格式化字符串 (Formatted String with padding and alignment)

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()函数,则不会显示字符串周围的引号,并且字符串长度也不清楚。

带数字的字符串format() (String format() with numbers)

There are many formatting options for numbers, let's look at some of them.

数字有许多格式设置选项,让我们看一下其中的一些。

为格式化的字符串指定符号(+,-) (Specifying a sign (+, -) for formatted string)

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.

请注意,在第二条语句中,空格被用作数字的前缀。 对于负数,始终使用负号(-)。

将整数格式化为不同的底数 (Format integers to different bases)

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

带复数的format() (format() with complex number)

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.

就像访问对象的属性一样。

使用逗号作为千位分隔符格式化数字 (Formatting numbers using comma as a thousands separator)

print('{:,}'.format(1234567890))

Output: 1,234,567,890

输出: 1,234,567,890

百分比,填充和舍入 (Percentage, Padding and Rounding)

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.

请注意,小数点后的舍入是根据默认舍入规则进行的。 另外,在数字前面进行填充。

调用str()和repr()函数 (Calling str() and repr() functions)

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

摘要 (Summary)

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:

参考:

. 检出完整的python脚本和更多Python示例。

翻译自:

转载地址:http://qamzd.baihongyu.com/

你可能感兴趣的文章
团队项目---测试与调试
查看>>
BZOJ 1699 [Usaco2007 Jan]Balanced Lineup排队
查看>>
关于uitableviewcell的accessoryType属性
查看>>
Spring Boot启动过程及回调接口汇总
查看>>
按位计数法
查看>>
17:网络编程
查看>>
Redis缓存方案
查看>>
LwIP buffer management, memory configuration options
查看>>
JMeter 聚合报告之 90% Line 参数说明
查看>>
Python环境——安装扩展库
查看>>
HTML常用标签
查看>>
Python MySQLdb 学习总结(转)
查看>>
Scrum Meeting 9
查看>>
uml 学习
查看>>
2、hibernate七步走完成增删改查
查看>>
移动Web开发规范
查看>>
Singly linked list algorithm implemented by Java
查看>>
金币阵列问题
查看>>
文件锁-fcntl flock lockf
查看>>
bzoj4318OSU &tyvj1952 Easy
查看>>