格式化字符串format函数使用方法

高洛峰
Release: 2017-03-23 15:00:51
Original
2949 people have browsed it

Format


一、语法

通过{} 和 : 来代替 %

二、事例

name = "bigberg"
age = 18
msg1="my name is {},and my age is {}.".format(name,age)
msg2="my name is {0},and my age is {1}.".format(name,age)
msg3="my name is {_name},and my age is {_age}.".format(_name=name,_age=age)
msg4="my name is {1},and my age is {0},and my brother's age is {0}.".format(age,name)
print(msg1)
print(msg2)
print(msg3)
print(msg4)
#输出
my name is bigberg,and my age is 18.
my name is bigberg,and my age is 18.
my name is bigberg,and my age is 18.
my name is bigberg,and my age is 18,and my brother's age is 18.
Copy after login

  字符串的format函数可以接受不限个参数,位置可以不按顺序,可以不用或者用多次,不过2.6不能为空{},2.7以后才可以

三、下标获取元素

info = ["bigberg",18]
msg='{0[0]},{0[1]}'.format(info)
print(msg)
#输出
bigberg,18
Copy after login

四、格式限定符

语法是 {:}

  1.填充与对齐

   填充和对齐常一起使用

  ^、<、>分别是居中 、左对齐、右对齐 ,后面带宽度。 后面带填充的字符,只能是一个字符,不指定默认用空格填充。

number = 234
print('{:>8}'.format(number))
print('{:*>8}'.format(number))
#输出
     234
*****234
Copy after login

  2.精度与类型f

num = 123.23423
print('{:.2f}'.format(num))
#输出
123.23
Copy after login

  其中 .2表示长度为2的精度,f 表示 float 类型

  3.进制

  b、d、o、x 分别表示 二进制、十进制、八进制和十六进制 

num = 25
print('{:b}'.format(num))
print('{:d}'.format(num))
print('{:o}'.format(num))
print('{:x}'.format(num))
#输出
11001
25
31
19
Copy after login

The above is the detailed content of 格式化字符串format函数使用方法. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!