python 碎片

Posted on Posted in python

python 利用字典模拟 switch-case

def pswitch(x):  
    return pswitch.dict.get(x,None)
                 
pswitch.dict = {'a':1, 'b':2, 'c':3}
print(pswitch('a'))
print(pswitch('d')) 

列表推导式

>>> [x for x in range(1, 11)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [x for x in range(1, 11) if 5 < x < 9]
[6, 7, 8]

字典

>>> {x:x+3 for x in range(1, 11) if x % 2 == 0}
{8: 11, 2: 5, 4: 7, 10: 13, 6: 9}

计数对象

>>> from collections import Counter
>>> c = Counter('liuhonghe')
>>> c
Counter({'h': 2, 'i': 1, 'n': 1, 'l': 1, 'u': 1, 'e': 1, 'o': 1, 'g': 1})
>>> c = Counter([1,1,1,3,4,5,6,7,8])
>>> c
Counter({1: 3, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1})
>>> c.most_common(1)
[(1, 3)]

生成包含大写字母和数字的随机字符串

In [1]: import random, string

In [2]: ''.join(random.choice(string.ascii_uppercase+string.digits) for _ in range(5))
Out[2]: 'UCXME'

字符串说明

import string               
print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits) # 0123456789
# 可以查看源码,搜索其中选项                                                                                                                                               
print(string) # 打印出string的位置, <module 'string' from '/usr/lib/python3.5/string.py'>

判断对象类型

In [1]: a = 2

In [2]: isinstance(a,(int,str,list))
Out[2]: True

检测字符串头尾

In [5]: a = '1.jpg'

In [6]: a.endswith(('.jpg','.png','.jpeg')) # 利用元祖进行多个判读,同理 startswith
Out[6]: True

简单的ftp服务器

  • -i 指定IP地址(默认为本机的IP地址)
  • -p 指定端口(默认为2121)
  • -w 写权限(默认为只读)
  • -d 指定目录 (默认为当前目录)
  • -u 指定用户名登录
  • -P 设置登录密码
pip install pyftpdlib
python -m pyftpdlib -p 21

查看环境版本

>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
>>> sys.version_info.major
3

时间比较

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2018, 6, 11, 7, 55, 50, 868752)
>>> datetime.now().strftime('%Y-%m-%d')
'2018-06-11'
>>> datetime.now().strftime('%Y-%m-%d') < '2019-09-11'
True
>>> datetime.now().strftime('%Y-%m-%d') < '2017-11-11'
False

with处理文本,同时处理多个

with open('input.txt', 'r') as source, open('output.txt', 'w') as target:
    target.write(source.read())
» 转载请注明来源:呢喃 » python 碎片

Leave a Reply

Your email address will not be published. Required fields are marked *

15 + 11 =