python中字符串格式化的两种方法


知识点汇总;
1-字符串格式化输出方法一: %
1-print('名字是 %s,年龄是%s' % (name ,age))
2- %s ---字符串-----相当于执行了str()
3- (name ,age) 只能是元组,不能是列表
4- 多个数据的打印,一定是元组
5- %d--十进制
6- %f--6位小数
7- %x--
8-指定长度打印----数值和字符串一样的
1- %5d 右对齐 ,不足左边补空格
2- -%5d 左对齐 ,不足右边补空格
3- 补0 %05d
9- 十六进制:%#x # 加一个 0x
10 小数--float
1- 默认是6位
2- 指定保留小数位数- %.3f-----进行了四舍五入
3- %6.3f ---- 6代表总长度(包括 . )
4- %08.3f ---- 补0

2-字符串格式化输出方法二: format()---固定的 {}
1- 顺序填坑:
1- 可以有元素多,不能有元素少!
print('名字是 {},年龄是 {}'.format(name ,age))

2- 下标填坑:
1- 不能下标越界 IndexError: tuple index out of range
print('名字是 {1},年龄是 {0}'.format(name ,age))

3- 变量方法
1- print('名字是 {name},年龄是 {age}'.format(name='tom' ,age = 18))

4-指定长度输出:
1- {:长度}
1- 数值型:右对齐,左补齐
2- 字符串:左对齐,右补齐
2- > 右对齐
3- < 左对齐
4- ^ 中间对齐 ---异或
5- 数值补0 ,一般是右对齐 , 左补0 ,不改变值
6- 字符串本身带花括号 {{}}

3- python 3.6 以后 f''
print(f'名字是{name},年龄是{age}')
4- 转义符
print('name is tom')
5- input()---控制台的终端输入
1- 有返回值---str
2- 如果对得到的值进行算术---int()、float()
3- 用户的输入是以一个回车符结束---不敲回车就死等

'''

'''
1- format
1- 顺序填坑
2- 下标填坑
3- 变量填坑 print('名字是{name},年龄是{age}'.format(name = 'tom',age = 18))
2- 中间对齐 ^

'''
name = 'tom'
age = 18
print(f'名字是:{name},年龄是:{age}')

fileDir1 = 'g:/test.py'
fileDir2 = 'g:\file\test.log'
fileDir3 = r'g:file est.log'


# print('名字是:{:>6},年龄是:{:0>6}'.format(name , age) )
# print('名字是:{1},年龄是:{0}'.format(name , age) )
# print('名字是:{name},年龄是:{age}'.format(name= 'tom' , age=18) )
'''
format:
1- 顺序-print('名字是:{},年龄是:{}'.format(name , age) )
2- 下标填坑-print('名字是:{1},年龄是:{0}'.format(name , age) )
3- 变量填坑-print('名字是:{name},年龄是:{age}'.format(name= 'tom' , age=18) )
> 右对齐 {:0>6} < 左对齐 ^中间对齐

'''

# print('%06.3f' % 3.1415926)#%f----默认是6
# print(hex(108))
# print('%#x' % 108)
# print('%#X' % 108)
# print('%5d' % 56)

 

 

# print('名字是:'+name+' 年龄是:'+str(age))
#
# print('名字是:%s,年龄是:%d' % (name,age))# %s 格式- str
# str1 = '名字是:%s,年龄是:%d' % (name,age)

我是kelly-凯莉 每天努力一点点,幸运就多一点点
原文地址:https://www.cnblogs.com/kelly11/p/11842354.html