1、切片的第三个参数是切片长度,为负数是从末尾开始
>>> string.digits
'0123456789'
>>> s="abcdef"
>>> s[::-1]
'fedcba'
>>> s[1:4:2]
'bd'
2、
>>> import sets
>>> s = sets.Set("i come china")
>>> s
Set(['a', ' ', 'c', 'e', 'i', 'h', 'm', 'o', 'n'])
>>> print s
Set(['a', ' ', 'c', 'e', 'i', 'h', 'm', 'o', 'n'])
>>> ss = map(str, s)
>>> ss
['a', ' ', 'c', 'e', 'i', 'h', 'm', 'o', 'n']
>>> list(s)
['a', ' ', 'c', 'e', 'i', 'h', 'm', 'o', 'n']
3、ord函数与chr函数与unichr
ord:将一个字符(形式如:'a' or "\xbc")转换成ASCII码数字或unicoce数字:
chr:将一个ASCII码数字换成相应的字符或存储形式('\xbc')
unichr:将一个unicode数字转换成相应的字符或存储形式('u\u2020')
>>> s = ord("\xbc")
>>> s
188
>>> c = chr(188)
>>> c
'\xbc'
>>> print c
>> x= ord("a")
>>> x
97
>>> x = ord("\xbc")
>>> x
188
>>> c = chr(188)
>>> c
'\xbc'
>>> c = chr(97)
>>> c
'a'
>>> u = ord(u"\u2020")
>>> u
8224
>>> u = unichr(8224)
>>> u
u'\u2020'
4、string模块 maketrans("", "") translate(dic, del)
#coding=utf-8
import string
def makefilter(keep):
allchars = string.maketrans('', '')
delchars = allchars.translate(allchars, keep)
def thefilter(s):
return s.translate(allchars, delchars)
return thefilter
if __name__ == "__main__":
just_vowels = makefilter('aeiouy')
print just_vowels('four score and seven years ago')
5、string.Template() && s.substitute()
>>> import string
>>> new = string.Template("i come $c")
>>> change = new.substitute({'c':'china'})
>>> print change
i come china
>>> change = new.substitute(c='china')
>>> print change
i come china
6、MAC地址转换
>>> str = "\xbc=\f4k>n" #MAC地址的字节流
>>> d = map(ord, list(str))
>>> d
[188, 61, 12, 52, 107, 62, 110]
>>> h = map(hex, d)
>>> h
['0xbc', '0x3d', '0xc', '0x34', '0x6b', '0x3e', '0x6e']
>>> l = [i[2:] for i in h]
>>> l
['bc', '3d', 'c', '34', '6b', '3e', '6e']
>>> ':'.join(l)
'bc:3d:c:34:6b:3e:6e'
7、IP地址转换
方法一:
>>> dst = "u0\x9d\xc9"
>>> '.'.join(map(str, map(ord, list(dst))))
'117.48.157.201'
方法二、 使用python socket模块
>>> dst = "u0\x9d\xc9"
>>> import socket
>>> d = socket.inet_ntoa(dst)
>>> d
'117.48.157.201'