How to use python’s format?
Python’s format function usage
It enhances the string formatting function. The basic syntax is to replace the previous % with {} and :. The format function can accept unlimited parameters, and the positions do not need to be in order.
**Example 1: The **format function can accept unlimited parameters, and the positions do not need to be in order.
"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 运行结果:'hello world' "{0} {1}".format("hello", "world") # 设置指定位置 运行结果:'hello world' "{1} {0} {1}".format("hello", "world") # 设置指定位置 运行结果:'world hello world'
Example 2: You can also set parameters.
print("网站名:{name}, 地址 {url}".format(name="Python教程", url="www.py.cn")) # 通过字典设置参数 site = {"name": "Python教程", "url": "www.py.cn"} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['Python教程', 'www.py.cn'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的 运行结果: 网站名:Python教程, 地址 www.py.cn 网站名:Python教程, 地址 www.py.cn 网站名:Python教程, 地址 www.py.cn
Example 3: You can also pass in the object to str.format():
class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
The output result is:
value 为: 6
Example 4: The following table shows str.format () Multiple methods of formatting numbers
print("{:.2f}".format(3.1415926)); 3.14
Number formatting methods
Number format output description
3.1415926 {:.2f} 3.14 Keep two decimal places
3.1415926 {: .2f} 3.14 Signed to two decimal places
-1 {: .2f} -1.00 Signed to two decimal places
2.71828 {:. 0f} 3 without decimal
5 {:0>2d} 05 Numeric zero padding (padding to the left, width is 2)
5 {:x
10 {:x##0.25 {:.2%} 25.00% Percent format
1000000000 {:.2e} 1.00e 09 Exponent notation 13 {:10d} 13 Right justified (default , width is 10) 13 {:13 {:^10d} 13 center-aligned (width is 10) '{:b}'.format(11) 1011 '{:d}'.format(11) 11 11's base '{:o}'.format (11) 13 '{:x}'.format(11) b '{:#x}'.format(11) 0xb '{: #X}'.format(11) 0XB^, are centered, left-aligned, and right-aligned respectively, followed by width, followed by : and filled with characters, which can only be one character , if not specified, it will be filled with spaces by default. means displaying before positive numbers and - before negative numbers; (space) means adding spaces before positive numbers b, d, o, x are binary, decimal, octal, and ten respectively Hexadecimal. Example 5: Give you a dictionary:t={‘year’:’2013’,’month’:’9’,’day’:’30’,’hour’:’16’,’minute’:’45’,’second’:’2’}Please output in this format: 2013-09-30 16:45:02
def data_to_str(d): ''' :param d: 日期字典 :return: str 格式化后的日期 ''' s1='{} {:>02} {:>02}'.format(t['year'],t['month'],t['day']) s2='{} {:>02} {:>02}'.format(t['hour'],t['minute'],t['second']) print(s1,s2) print('-'.join(s1.split()),end=' ') print(':'.join(s2.split())) return 0 t={'year':'2013','month':'9','day':'30','hour':'16','minute':'45','second':'2'} print(data_to_str(t))Run results:
2013 09 30 16 45 02 2013-09-30 16:45:02Related recommendations: "
Python Tutorial
"The above is the detailed content of How to use python's format. For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download
The most popular open source editor
