Python占位符介绍及操作方法
Posted 金钢911
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python占位符介绍及操作方法相关的知识,希望对你有一定的参考价值。
1,常用占用符:
常见的占位符有:
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数
使用方法:
tpl
=
"i am %s"
%
"alex"
tpl
=
"i am %s age %d"
%
(
"alex"
,
18
)
tpl
=
"i am %(name)s age %(age)d"
%
{
"name"
:
"alex"
,
"age"
:
18
}
tpl
=
"percent %.2f"
%
99.97623
tpl
=
"i am %(pp).2f"
%
{
"pp"
:
123.425556
, }
tpl
=
"i am %.2f %%"
%
{
"pp"
:
123.425556
, }
2,Format方法:
tpl
=
"i am {}, age {}, {}"
.
format
(
"seven"
,
18
,
‘alex‘
)
tpl
=
"i am {}, age {}, {}"
.
format
(
*
[
"seven"
,
18
,
‘alex‘
])
tpl
=
"i am {0}, age {1}, really {0}"
.
format
(
"seven"
,
18
)
tpl
=
"i am {0}, age {1}, really {0}"
.
format
(
*
[
"seven"
,
18
])
tpl
=
"i am {name}, age {age}, really {name}"
.
format
(name
=
"seven"
, age
=
18
)
tpl
=
"i am {name}, age {age}, really {name}"
.
format
(
*
*
{
"name"
:
"seven"
,
"age"
:
18
})
tpl
=
"i am {0[0]}, age {0[1]}, really {0[2]}"
.
format
([
1
,
2
,
3
], [
11
,
22
,
33
])
tpl
=
"i am {:s}, age {:d}, money {:f}"
.
format
(
"seven"
,
18
,
88888.1
)
tpl
=
"i am {:s}, age {:d}"
.
format
(
*
[
"seven"
,
18
])
tpl
=
"i am {name:s}, age {age:d}"
.
format
(name
=
"seven"
, age
=
18
)
tpl
=
"i am {name:s}, age {age:d}"
.
format
(
*
*
{
"name"
:
"seven"
,
"age"
:
18
})
tpl
=
"numbers: {:b},{:o},{:d},{:x},{:X}, {:%}"
.
format
(
15
,
15
,
15
,
15
,
15
,
15.87623
,
2
)
tpl
=
"numbers: {:b},{:o},{:d},{:x},{:X}, {:%}"
.
format
(
15
,
15
,
15
,
15
,
15
,
15.87623
,
2
)
tpl
=
"numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}"
.
format
(
15
)
tpl
=
"numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}"
.
format
(num
=
15
)
以上是关于Python占位符介绍及操作方法的主要内容,如果未能解决你的问题,请参考以下文章