Python tutorial: Python3 the format string formatting function explain (a)

Python tutorial: Python3 the format string formatting function explain (a)

Outline

In Python3, the formatting operation by the string format () method or f'string 'implemented. The string of format compared to the old version, format () method has more features, more convenient to operate, but also more readable. The string will function as a template for formatting parameters passed, and braces {}% instead of as a special character.

Location settings

The default position

Position is not specified format, formatted in the default order

S = 'I {} {}, and I'am learning'.format('like', 'Python')
print(S)
复制代码

Sample results:

I like Python, and I'am learning
复制代码

Set location

Setting numerical order specified location formatted

S = 'I {0} {1}, and I'am learning'.format('like', 'Python')
print(S)
# 打乱顺序
S = 'I {1} {0} {1}, and I'am learning'.format('like', 'Python')
print(S)
复制代码

Sample results:

I like Python, and I'am learning
I Python like Python, and I'am learning
复制代码

Set keyword

Set keyword specifies formatted content

S = 'I {l} {p}, and I'am learning'.format(p='Python', l='like')
print(S)
S = 'I {p} {l}, and I'am learning'.format(p='Python', l='like')
print(S)
复制代码

Sample results:

I like Python, and I'am learning
I Python like, and I'am learning
复制代码

Parameter passing

We can do this format string types of parameters, i.e., string variables or the like is not limited to numbers.

Tuples parameter passing

Using the tuple parameter passing, parameter passing in the form * tuple

# 定义一个元组
T = 'like', 'Python'
# 不指定顺序
S = 'I {} {}, and I'am learning'.format(*T)
print(S)
# 指定顺序
S = 'I {0} {1}, and I'am learning'.format(*T)
print(S)
复制代码

Sample results:

I like Python, and I'am learning
I like Python, and I'am learning
复制代码

Biography Reference Dictionary

# 定义一个字典
D = {'l':'like', 'p':'Python'}
# 指定键确定顺序
S = 'I {l} {p}, and I'am learning'.format(**D)
print(S)
复制代码

Sample results:

I like Python, and I'am learning
复制代码

List parameter passing

# 定义一个列表
L0 = ['like', 'Python']
L1 = [' ', 'Lerning']
# `[]`前的0、1用于指定传入的列表顺序
S = 'I {0[0]} {1[1]}, and I'am learning'.format(L0, L1)
print(S)
复制代码

Sample results:

I like Lerning, and I'am learning
复制代码

The next issue of Python tutorials will continue to update everyone!


Reproduced in: https: //juejin.im/post/5cf4db3651882556174dd700

Guess you like

Origin blog.csdn.net/weixin_34082695/article/details/91482066