目录python
程序中常常会出现这样的 场景:要求用户输入信息,而后打印成固定的格式code
好比要求用户输入用户名和年龄,而后打印以下格式:orm
My name is xxx,my age is xxx.
很明显用逗号进行字符串拼接,只能把用户输入的姓名和年龄放到末尾,没法放到指定的xxx位置,并且数字也必须通过str(数字)的转换才能与字符串进行拼接。索引
可是用占位符就很简单,如:==%s(针对全部数据类型),%d(仅仅针对数字类型)==字符串
name = 'python' age = 30 print('My name is %s, my age is %s' % (name, age)) #输出: My name is python, my age is 30
age = 30 print(' my age is %s' % age) #输出: my age is 30
name = 'python' age = 30 print("hello,{},you are {}".format(name,age)) #输出: hello,python,you are 30
name = 'python' age = 30 print("hello,{1},you are {0}-{0}".format(age,name))#索引是根据format后的数据进行的哦 #输出: hello,python,you are 30-30
name = 'python' age = 30 print("hello,{name},you are {age}".format(age=age, name=name)) #输出: hello,python,you are 30
==比较简单,实用==string
==f 或者 F==均可以哦it
让字符和数字可以直接相加哦form
name = 'python' age = 30 print(f"hello,{name},you are {age}") #输出: hello,python,you are 30
name = 'python' age = 30 print(F"hello,{name},you are {age}") 输出: hello,python,you are 30
name = 'python' age = 30 print(F"{age * 2}") 输出: 60
fac = 100.1001 print(f"{fac:.2f}") # 保留小数点后俩位 #保存在*右边,*20个,fac占8位,剩余在右边,*可替换 print(f"{fac:*>20}") print(f"{fac:*<20}") print(f"{fac:*^20}") print(f"{fac:*^20.2f}") #输出: 100.10 ************100.1001 100.1001************ ******100.1001****** *******100.10*******