search
HomeBackend DevelopmentPython Tutorial跟老齐学Python之从格式化表达式到方法

现在我们就格式化方法做一个详细一点的交代。

基本的操作

所谓格式化方法,就是可以先建立一个输出字符串的模板,然后用format来填充模板的内容。

复制代码 代码如下:

>>> #先做一个字符串模板
>>> template = "My name is {0}. My website is {1}. I am writing {2}."

>>> #用format依次对应模板中的序号内容
>>> template.format("qiwsir","qiwsir.github.io","python")
'My name is qiwsir. My website is qiwsir.github.io. I am writing python.'

当然,上面的操作如果你要这样做,也是可以的:

复制代码 代码如下:

>>> "My name is {0}. My website is {1}. I am writing {2}.".format("qiwsir","qiwsir.github.io","python")
'My name is qiwsir. My website is qiwsir.github.io. I am writing python.'

这些,跟用%写的表达式没有什么太大的区别。不过看官别着急,一般小孩子都区别不到,长大了才有区别的。慢慢看,慢慢实验。

除了可以按照对应顺序(类似占位符了)填充模板中的位置之外,还能这样,用关键字来指明所应该田中的内容。

复制代码 代码如下:

>>> template = "My name is {name}. My website is {site}"
>>> template.format(site='qiwsir.github.io', name='qiwsir')
'My name is qiwsir. My website is qiwsir.github.io'

关键词所指定的内容,也不一定非是str,其它的数据类型也可以。此外,关键词和前面的位置编号,还可以混用。比如:

复制代码 代码如下:

>>> "{number} is in {all}. {0} are my number.".format("seven",number=7,all=[1,2,3,4,5,6,7,8,9,0])
'7 is in [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]. seven are my number.'

是不是开始感觉有点意思了?看输出结果,就知道,经过format方法得到是一个新的str。

序列对象的偏移量

有这样一个要求:在输出中,显示出一个单词的第一个字母和第三个个字母。比如单词python,要告诉看官,第一字母是p,第三个字母是t。

这个问题并不难。实现方法也不少,这里主要是要展示一下偏移量在format中的应用。

复制代码 代码如下:

>>> template = "First={0[0]}, Third={0[2]}"
>>> template.format(word)
'First=p, Third=t'

list也是序列类型的,其偏移量也可。

复制代码 代码如下:

>>> word_lst = list(word)
>>> word_lst
['p', 'y', 't', 'h', 'o', 'n']
>>> template
'First={0[0]}, Third={0[2]}'
>>> template.format(word_lst)
'First=p, Third=t'

对上面的综合一下,稍微啰嗦一点的实验:

复制代码 代码如下:

>>> template = "The word is {0}, Its first is {0[0]}. Another word is {1}, Its second is {1[1]}."
>>> template.format("python","learn")
'The word is python, Its first is p. Another word is learn, Its second is e.'

>>> "{name}\'s first is {name[0]}".format(name="qiwsir")    #指定关键词的值的偏移量
"qiwsir's first is q"

值得注意的是,偏移量在序列类型的数据中,因为可以是负数,即能够从右边开始计数。

复制代码 代码如下:

>>> word
'python'
>>> word[-1]
'n'
>>> word[-2]
'o'

但是,在模板中,无法使用负数的偏移量。

复制代码 代码如下:

>>> "First={0[0]}, End={0[-1]}".format(word) #报错
Traceback (most recent call last):
  File "", line 1, in
TypeError: string indices must be integers, not str

>>> "First={0[0]}, End={0[5]}".format(word)  #把-1改为5就可以了。
'First=p, End=n'

当然,放到模板外面是完全可行的。这样就好了:

复制代码 代码如下:

>>> "First={0}, End={1}".format(word[0],word[-1])
'First=p, End=n'

dictionary的键

直接上实验,先观察,再得结论

复制代码 代码如下:

>>> myinfo
{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}
>>> template = "I am {0[name]}"
>>> template.format(myinfo)
'I am qiwsir'
>>> template = "I am {0[name]}. My QQ is {qq}"
>>> template.format(myinfo,qq="26066913")
'I am qiwsir. My QQ is 26066913'

位置后面跟键,就能得到format的参数中字典的键对应的值。太罗嗦了吧,看例子就明白了。出了根据位置得到,还能够根据关键词得到:

复制代码 代码如下:

>>> myinfo
{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}
>>> "my website is {info[website]}, and I like {0}".format("python",info=myinfo)    #关键词info引用的是一个字典
'my website is qiwsir.github.io, and I like python'

模板中添加属性

看标题不懂在说什么。那就看实验吧。

复制代码 代码如下:

>>> import math
>>> "PI is {PI.pi}".format(PI=math)
'PI is 3.14159265359'

这是用关键词,下面换个稍微复杂点,用位置的。

复制代码 代码如下:

>>> import sys,math
>>> 'PI is {0.pi}. My lptop runs {1.platform}'.format(math,sys)
'PI is 3.14159265359. My lptop runs linux2'

看官理解了吧。

其它进制

在这个世界上的数学领域,除了有我们常常用到的十进制、十二进制(几点了,这是你我常用到的,钟表面就是12进制)、六十进制(这个你也熟悉的)外,还有别的进制,比如二进制、八进制、十六进制等等。此处不谈进制问题,有兴趣详细了解,请各自google。不过,进制的确在计算机上很重要的。因为机器在最底层是用二进制的。

这里只是说明一下输出时候的进制问题。

>>> "{0:X}, {1:o}, {2:b}".format(255,255,255)
'FF, 377, 11111111'
X:十六进制,Hex
o:八进制,octal
b:二进制,binary
顺便补充,对于数的格式化方法输出和格式化表达式一样,就不赘述了。

在格式化方法中,还能够指定字符宽度,左右对齐等简单排版格式,不过,在我的经验中,这些似乎用的不怎么多。如果看官需要,可以google或者到官方文档看看即可。

关于格式化表达式和格式化方法,有的人进行了不少比较,有的人说用这个,有的人倾向用那个。我的建议是,你用哪个顺手就用哪个。切忌门派之见呀。不过,有人传说格式化表达式可能在将来某个版本中废除。那是将来的事情,将来再说好了。现在,你就捡着顺手的用吧。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.