Python 3.3 Tutorial Notes - 5:Input and Output

本文介绍了Python中字符串处理的方法,包括格式化、对齐及填充等,并详细解释了str()和repr()函数的区别。此外,还讲解了文件读写操作及pickle模块的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Format string: str.Format()
2. Convert to string: str(), repr()
     2.1 The str() function is meant to return representations of values which are fairly human-readable
     2.2 repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax).
     2.3 For objects which don’t have a particular representation for human consumption, str() will return the same value as repr().
     2.4 The repr() of a string adds string quotes and backslashes
"'hello\\r'"
>>> s='hello\n'
>>> str(s)
'hello\n'
>>> repr(s)
"'hello\\n'"
3. str.rjust(), str.ljust(), str.center()
4. str.zfill()
5. str.format()
     5.1 >>> print(’The story of {0}, {1}, and {other}.’.format(’Bill’, ’Manfred’, other=’Georg’))
     5.2 >>> print(’We are the {} who say "{}!"’.format(’knights’, ’Ni’))
     5.3 >>> print(’The value of PI is approximately {!r}.’.format(math.pi))
          5.3.1 ’!a’ (apply ascii()), 
          5.3.2 ’!s’ (apply str()) 
          5.3.3 ’!r’ (apply repr())
     5.4 >>> table = {’Sjoerd’: 4127, ’Jack’: 4098, ’Dcab’: 8637678}
          >>> print(’Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}’.format(table))
          or
          >>> print(’Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}’.format(**table))
     5.5 (old style) print(’The value of PI is approximately %5.3f.’ % math.pi)
6. open() return file object
     6.1 Reading in text mode (default UTF-8), platform-specific line endings will be converted to \n automatically. Similar translation happens on writing.
7. f.read(size)
     7.1 if no size or size is negative, read the whole file
     7.2 read to the end, return empty string ('')
8. f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.
9. For reading lines from a file, you can loop over the file object.
>>> for line in f:
... print(line, end=’’)
...
10. f.write() returns how many bytes written into file.
11. f.seek(), f.tell()
12.   pickle  Module
     12.1 pickling: take any Python object to a string
     12.2 unpickling: reconstruct the object from a string
     12.3 EASY TO USE, WIDELY SUPPORTED!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值