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 tuple and list as argument for index based replacement.我们可以提供诸如元组和列表之类的序列作为基于索引的替换的参数。
  • We can provide dictionary 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 above
print("I like {} and {}".format("Java", "Python"))# index can be in any order
print("I like {1} and {0}".format("Java", "Python"))

Output:

输出:

My Name is Pankaj
I like Java and Python
I like Java and Python
I like Python and Java

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

# unpacking from sequences
t = ("Java", "Python")
print("I like {1} and {0}".format(*t))l = ["Java", "Python"]
print("I like {} and {}".format(*t))

Output:

输出:

I like Python and Java
I 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 = 0name = ''def __init__(self, i, n):self.id = iself.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.2300001.230000; -1.230000
1.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: 11100
int: 28;  hex: 1c;  oct: 34;  bin: 11100
int: 28;  hex: 0x1c;  oct: 0o34;  bin: 0b11100

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

complex_number = 4 + 2j
print("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.3422222.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: Data
Test 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: API Doc

参考: API文档

GitHub Repository.GitHub存储库中检出完整的python脚本和更多Python示例。

翻译自: https://www.journaldev.com/23487/python-string-format

Python字符串格式()相关推荐

  1. python使用字典格式化字符串-Python字符串格式方式 %s format()

    python中格式化字符串的方式有两种,一种是使用"%s"的方式,一种是str.format()的方式,接下来就对这两种方式做个介绍 1.%s的方式 两种用法,第一种是在字符串中使 ...

  2. Python字符串格式:%vs.format

    Often the string formatters in python are referred to as old style and new style. The old-style is ' ...

  3. python 字符串格式符

    # ''' # 字符串除了用format()方法进行格式化外,还可以使用格式化表达式来处理字符串.字符串格式化表达式用%表示,%之前需要进行格式化的 # 字符串.字符串格式化表达式用%表示,%之前为需 ...

  4. python字符串格式时间转化为时间戳

    1.问题: 在服务请求记录时间时,往往是毫秒级的,在秒上计数会有小数点,例如 dt= '2020-09-09 15:03:56.742' time.strptime支持的几种数字类型如下: decim ...

  5. python什么意思g_在laymans术语中,Python字符串格式“g”实际上是什么意思?

    这些例子可能是说明性的:>>> numbers = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001] >>> for ...

  6. python什么意思g_在外行人看来,Python字符串格式“g”实际意味着什么?

    这些例子可能是说明性的: >>> numbers = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001] >>> for ...

  7. Python字符串串联

    String Concatenation is a very common operation in programming. Python String Concatenation can be d ...

  8. Python新型字符串格式漏洞分析

    前言 本文对Python引入的一种格式化字符串的新型语法的安全漏洞进行了深入的分析,并提供了相应的安全解决方案. 当我们对不可信的用户输入使用str.format的时候,将会带来安全隐患--对于这个问 ...

  9. Python语言学习:基于python五种方法实现使用某函数名【func_01】的字符串格式('func_01')来调用该函数【func_01】执行功能

    Python语言学习:基于python五种方法实现使用某函数名[func_01]的字符串格式('func_01')来调用该函数[func_01]执行功能 目录 问题提出 代码五种设计思路 T1方法:e ...

最新文章

  1. 北京搜狗已签算法30W,西安银行总包20W,要不要毁约去银行?
  2. 手把手教 | 使用Keras构造日文的神经网络语言模型(内附源码)
  3. 计算机教师资格证报考科目,还在纠结报考教师资格证该选哪个科目呢?看完这篇,你不再迷茫...
  4. [原]java开发中遇到的问题及解决方法(持续更新)
  5. 今天是个特殊的一天,有意义的一天,值得纪念的一天~
  6. 一个兼容所有浏览器的阻止事件冒泡方法
  7. anaconda新建python2环境安装不了jupyterlab_在Mac下安装anaconda及配置jupyterLab和PyTorch的方法...
  8. 我的docker随笔29:oracle数据库部署
  9. 计算机奖状模板,制作电子奖状
  10. zmap zgrab 使用
  11. 蝸居…唯一有共鳴的戲劇
  12. 扫地机器人拖实木地板_扫地机器人会不会损坏高档木地板
  13. Netty 大文件传输
  14. List<?>和list的区别
  15. ShareSDK快速集成
  16. 在Linux系统中解决 swap file “*.swp”already exists!问题
  17. 22款奔驰GLC260L改装23P驾驶辅助系统,这几大功能你还是有必要知道的!
  18. Excel如何提取含有关键词的所有数据
  19. 【2023 阿里云云计算工程师 ACP 认证练习题库】01、VPC 专有网络题库
  20. 运维之道 | PSSH 自动化集群管理、自动化脚本管理

热门文章

  1. 安装SQL Server2008,要重启机器,解决办法
  2. 读jQuery源码 jQuery.data
  3. win7的centos虚拟机上搭建mysql5.6服务
  4. 【转】[Python Tip]如何在Windows下方便地进入命令行运行程序
  5. [转载] Python中的string模块的学习
  6. E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/t
  7. 接口jdk1.8与jdk1.9新特性
  8. JavaScriptjQuery.检测相等和存在
  9. 项目需求:基于微信平台的拼团活动系统
  10. MyBatis基础入门--知识点总结