day02 格式化字符串
字符格式化2019-04-01
方法一
通过f + {} 格式化字符串
name = input("Name: ")
age = input("Age:")
score = input("Score: ")
info = f'''
--------------------------info about {name}
Name: {name}
Age: {age}
Score: {score}
'''
print(info)
格式化小数点
score = int(input("Score: "))
print(f'Score:{score:.2f}') ps:这样用户只能输入整数,然后程序会自动加两个0
格式化输入整数
score = float(input("Score: "))
print(f'Score:{score:.2f}')
格式化整形
score = int(input("Score: "))
print(f'Score:{score:d}')
方法二:
通过%号占位符: %s 标识字符串 %d表示只能是数字int类型 %f表示浮点数(ps:浮点数默认是六位,可以自己加参数指定具体位数)
name = input("Name: ")
age = input("Age:")
score = input("Score: ")
info = '''
---------------------info about %s-------------------------
Name: %s
Age: %d
Score: %.3f
''' %(name,name,int(age),float(score))
print(info)
方法三:
通过format来格式化
print("我叫%s,来自%s,喜欢%s" %("ivy","China","reading"))
print("我叫{},来自{},喜欢{}" .format("Ivy","GuiZhou","reading"))
print("我叫{1},来自{2},喜欢{0}" .format("Ivy","reading","GuiZhou"))
print("我叫{name},来自{address},喜欢{habby}" .format(name="Ivy",habby="reading",address="GuiZhou"))
ps:通过format格式化的时候do not forget format前面有一个点
We are down, but not beaten. tested but not defeated.