python字符串格式化方法%s和format函数

1.%s方法

一个例子

print("my name is %s and i am %d years old" %("xiaoming",18)

输出结果:my  name is xiaoming and i am 18 years old

而且也可以用字典的形式进行表示:

print("my name is %(name)s and i am %(year)d years old" %{"year":18,"name":"xiaoming"}

下面是常用字符格式
%% 百分号标记 #就是输出一个%

%c 字符及其ASCII码

%s 字符串

%d 有符号整数(十进制)

%u 无符号整数(十进制)

%o 无符号整数(八进制)

%x 无符号整数(十六进制)

%X 无符号整数(十六进制大写字符)

%e 浮点数字(科学计数法)

%E 浮点数字(科学计数法,用E代替e)

%f 浮点数字(用小数点符号)

%g 浮点数字(根据值的大小采用%e或%f)

%G 浮点数字(类似于%g)

%p 指针(用十六进制打印值的内存地址)

%n 存储输出字符的数量放进参数列表的下一个变量中

2.format()函数

在python2.6开始,就新增加了一个字符串格式化字符的函数str.format(),此函数可以快速的处理各种字符串,增强了字符串格式化的功能。基本语法是使用{}和:来替代%。format函数可以接受不限各参数,位置可以不按照顺序

>> "{} {}".format("hello","world")#设置指定位置,按默认顺序
'hello world'


>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'


>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'
print("姓名:{name}, 年龄 {year}".format(name="xiaoming", year=18))

# 通过字典设置参数
site = {"name": "xiaoming", "year": 18}
print("网站名:{name}, 地址 {url}".format(**site))

# 通过列表索引设置参数
my_list = ['xiaoming',18]
print("姓名:{0[0]}, 年龄 {0[1]}".format(my_list))  # "0" 是可选的
原文地址:https://www.cnblogs.com/qiujichu/p/10663197.html