Python cookbook 学习笔记一

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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值