您的位置:首页 > 编程语言 > Python开发

Python学习---读过《深入Python3》有感2

2011-11-16 23:03 246 查看
不用多说,附上代码:

__author__ = 'minggxu9'
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}

def approximate_size(size, a_kilobyte_is_1024_bytes=True):
'''Convert a file size to human-readable form.

Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 1000

Returns: string

'''
if size < 0:
raise ValueError('number must be non-negative')

multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
for suffix in SUFFIXES[multiple]:
size /= multiple
if size < multiple:
return '{0:.1f} {1}'.format(size, suffix)

raise ValueError('number too large')

query = 'user=pilgrim&database=master&password=PapayaWhip'
a_list = query.split('&')
print(a_list)
a_list_of_lists = [v.split('=') for v in a_list]
print(a_list_of_lists)

a_dict = dict(a_list_of_lists)
print(a_dict)

s = '''Finished files are the re-
sult of years of scientif-
ic study combined with the
experience of years.'''
print(s)
print(len(s))
print(s.splitlines())
print(s.lower())
print(s.lower().count('f')   )

#格式化字符串,格式化说明符
print('{0:.1f} {1}'.format(698.24, 'GB'))

#定义函数
def goOther(a_kilobyte_is_1024_bytes=True):
if  a_kilobyte_is_1024_bytes:
return '{0:.1f} {1}'.format(4444.14, 'gb')

print( goOther())

si_suffixes=['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
print('1000{0[0]} = 1{0[1]}'.format(si_suffixes))
'''
这一句看上去有些复杂,其实不是这样的。{0}代表传递给format()方法的第一个参数,
即si_suffixes。注意si_suffixes是一个列表。所以{0[0]}指代si_suffixes的第一个元素,即'KB'。
同时,{0[1]}指代该列表的第二个元素,即:'MB'。大括号以外的内容 — 包括1000,等号,
还有空格等 — 则按原样输出。语句最后返回字符串为'1000KB = 1MB'。
'''

username = 'mark'
password = 'PapayaWhip'
print("{0}'s password is {1}".format(username, password))

#字符串的分片
a_string = 'My alphabet starts where your alphabet ends.'
print(a_string[3:11])

print( a_string[3:-3])
print( a_string[0:2] )
print(a_string[:18] )
print(a_string[18:])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: