Python学习笔记3-字符串

格式化字符串/复合字段名

>>> import humansize
>>> si_suffixes = humansize.SUFFIXES[1000]
>>> si_suffixes
['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']


>>> '1000{0[0]} = 1{0[1]}'.format(si_suffixes)
'1000KB = 1MB'

 

>>> import humansize
>>> import sys
>>> '1MB = 1000{0.modules[humansize].SUFFIXES[1000][0]}'.format(sys)
'1MB = 1000KB'

 

Sys.modules 是一个保存当前python实例中搜有已导入模块的字典。模块的名字为键,模块自身为值。

 

 

>>> s = '''finished files are the re-

sults of years of scientific study combined with the

experience of years. ‘''

 

>>> s.splitlines()

['finished files are the re-', 'sults of years of scientific study combined with the', 'experience of years. ‘]

 

>>> print(s.lower())

finished files are the re-

sults of years of scientific study combined with the

experience of years. 

 

 

 

>>> a_list = query.split("&")

>>> a_list

['user=pilgrim', 'database=master', ‘password=PapayaWhip']

 

>>> a_list_of_list = [v.split('=',1) for v in a_list]

>>> a_list_of_list

[['user', 'pilgrim'], ['database', 'master'], ['password', ‘PapayaWhip']]

 

>>> a_dict = dict(a_list_of_list)

>>> a_dict

{'password': 'PapayaWhip', 'database': 'master', 'user': ‘pilgrim'}

  

split()-根据指定的分隔符,将字符串分隔成一个字符串列表。

dict() - 将包含列表的列表转换成字典对象

 

 

字符串的分片

 

>>> a_string = "My alphabet starts where your alphabet ends."

>>> a_string[3:11]

‘alphabet'

 

>>> a_string[3:-3]

'alphabet starts where your alphabet en’

 

>>> a_string[:18]

'My alphabet starts’

 

>>> a_string[18:]

' where your alphabet ends.'

 

 

String VS. Bytes

 

Bytes对象的定义:b’ ’, eg: by = b’abcd\x65’

Bytes对象不能改变其值,但可以通过内置函数bytearry()将bytes对象转化成bytearry对象,bytearry对象的值可改变

 

 

>>> by = b'abcd\x65'

>>> barr = bytearray(by)

>>> barr

bytearray(b'abcde')

 

>>> barr[0]=102

>>> barr

bytearray(b'fbcde')

 

 

>>> a_string = "dive into python"

>>> by = a_string.encode('utf-8')
>>> by
b'dive into python'

>>> roundtrip = by.decode('big5')
>>> roundtrip
'dive into python'

 

string.encode() -- 使用某种编码方式作为参数,将字符串转化为bytes对象。

bytes.decode() -- 使用某种编码方式作为参数,将bytes对象转化成字符串对象。

 

posted @ 2015-05-04 20:44  summerlong  阅读(589)  评论(0编辑  收藏  举报