程序员的公众号:源1024,获取更多资料,无加密无套路!
最近整理了一波电子书籍资料,包含《Effective Java中文版 第2版》《深入JAVA虚拟机》,《重构改善既有代码设计》,《MySQL高性能-第3版》,《Java并发编程实战》等等
获取方式: 关注公众号并回复 电子书 领取,更多内容持续奉上
Python两种输出值的方式:表达式语句和 print() 函数。
将输出的值转成字符串,可以使用 repr() 或 str() 函数来实现
| str() | 返回一个用户易读的表达形式 |
| repr() | 将对象转化为供解释器易读的形式,返回一个对象的 string 格式 |
- a = 'hello world'
- print(str(a))
- print(repr(a))
-
- #输出
- hello world
- 'hello world'
- '''
- repr() 函数还可以转义字符串中的特殊字符
- '''
- a = 'hello,你好\n'
- print(repr(a))
-
- #输出
- 'hello,你好\n'
str.rjust(width),将字符串靠右,左边填充空格
width:表示字符串的总长度
-
- '''
- rjust() 方法, 它可以将字符串靠右, 并在左边填充空格
- ljust() 和 center()
- '''
-
- print(repr('a').rjust(10))
- print(repr('a').ljust(10))
- print(repr('a').center(10))
-
- #输出
- 'a'
- 'a'
- 'a'
str.zfill(width)
width表示进行补零之后的字符串的长度,如果width小于等于原字符串的长度,那么字符串不会有任何变化。
- print('a'.zfill(3))
- print('12345'.zfill(3))
-
- #输出
- 00a
- 12345
str.format() 函数来格式化输出值
- '''
- str.format() 的基本使用
- '''
- print('{0} {1}'.format('hello', 'Python'))
- print('{name}的年龄是: {age}'.format(name='幻刺', age='15'))
- #结合使用
- print('{0}的年龄是: {1},在 {school} 上学'.format('幻刺', '15',school = '机关小学'))
-
- #输出
-
- hello Python
- 幻刺的年龄是: 15
- 幻刺的年龄是: 15,在 机关小学 上学
