%和format
格式化字符串主要有两种
<code>% 和 format</code>
但format是2.6之后的新特性。
so,推荐format
1,区别
demo:
# 坐标
c = (1, 2)
s1 = '坐标:%s' % c
这样便会报错:<code>TypeError: not all arguments converted during string formatting</code>
需要再进行修改,如示,%和format
s2 = '坐标:%s' % (c,)
print(s1) # 坐标:[1, 2]
s1 = '坐标:{}'.format(c)
print(s1) # 坐标:[1, 2]
2,新特性f-strings,仅限3.6以后
name = "tom"
age = 10
a = f"name:{name},age:{aeg}"
print(a)
常用语法
0,默认传值
print("name:{},age:{}".format("tom",18))
# name:tom,age:10
1,通过位置
date = ['tom',18]
print("name:{0},age:{1}".format(*data))
# name:tom,age:10
2,通过关键字,即数据是字典序
data = {"name": "tom", "age": 18}
print("name:{name},age:{age}".format(**data))
# name:tom,age:18
3,通过下标
data = ['tom', 10]
print("{0[0]} is {0[1]} year old".format(data))
# tom is 10 year old
4,通过对象属性
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "name:{self.name}, age:{self.age}".format(self=self)
p = Person("tom", 18)
print(str(p))
# name:tom, age:18
5,精度和类型
a = "{:.2f}".format(3.1415926)
print(a)
# 3.14
6,千位分隔符
a = "{:,}".format(1234567890)
print(a)
# '1,234,567,890'
拜师教育学员文章:作者:夏天老师,
转载或复制请以 超链接形式 并注明出处 拜师资源博客。
原文地址:《格式化字符串–format》 发布于2020-09-09
评论 抢沙发