Python中字符串的学习
Python中字符串的学习
一、字符串的格式化输出
- % 占位符
- %s 字符串
- %d integer
- %x 十六进制 integer
- %f float
- 指定长度
- %5d 右对齐,不足左边补空格
- %-5d - 代表左对齐,不足右边默认补空格
- %05d 右对齐,不足左边补0
-浮点数:- %f 默认是输出6位有效数据, 会进行四舍五入
- %.2f 指定小数点位数的输出 保留小数点后2位
- ‘%4.8f‘ 4代表整个浮点数的长度,包括小数,只有当
字符串的长度大于4位才起作用.不足4位空格补足,可以用%04.8使用0补足空格
二、字符串的format方法
- 顺序填坑:{} 占位符
- 下标填坑
- 变量填坑
- 对齐
- {:5} 指定输出长度=5
- 字符串 {:5}--左对齐
- 数值 {:5}--右对齐
- 使用 > < 可以避免字符串/数值对齐方法不一致
- > 右对齐
- < 左对齐
- 中间对齐 ^
- 不足的长度用*表示
三、格式化 f‘‘
- python3.6 后的版本支持。
- f‘名字是:{name},年龄是:{age}‘
四、测试代码:
name = 'xiaolee' age = 45 height = 1.7234782342 intro1 = 'My name is %s, I\'m %d years old, and my height is %f Metres.' intro2 = 'My name is %s, I\'m %10d years old, and my height is %.2f Metres.' intro3 = 'My name is %s, I\'m %-10d years old, and my height is %4.2f Metres.' intro4 = 'My name is %s, I\'m %010d years old, and my height is %08.2f Metres.' intro5 = 'My name is %s, I\'m %x years old, and my height is %08.2f Metres.' intro6 = 'My name is {}, I\'m {} years old, and my height is {} Metres.' intro7 = 'My name is {2}, I\'m {1} years old, and my {0} is %08.2f Metres.' intro8 = 'My name is {name0}, I\'m {age0} years old, and my height is {height0} Metres.' intro9 = 'My name is {0:*<15}, I\'m {1:*>11} years old, and my height is {2:*^20} Metres.' introA = 'My name is {0:<15}, I\'m {1:>11} years old, and my height is {2:^20} Metres.' introB = 'My name is {0:#<15}, I\'m {1:$>11} years old, and my height is {2:8^20} Metres.' introC = f'My name is {name}, I\'m {age} years old, and my height is {height} Metres.' print(intro1 % (name, age, height)) print(intro2 % (name, age, height)) print(intro3 % (name, age, height)) print(intro4 % (name, age, height)) print(intro5 % (name, age, height)) print(intro6.format(name, age, height)) print(intro7.format(height, age, name)) print(intro8.format(age0=age, name0=name, height0=height)) print(intro9.format(name, age, height)) print(introA.format(name, age, height)) print(introB.format(name, age, height)) print(introC)
程序执行结果:
本文主要参照这篇博文,测试程序重新写。
Python 字符串格式化输出的3种方式