知乎专栏 |
http://docs.python.org/library/types.html
>>> type( [] ) == list True >>> type( {} ) == dict True >>> type( "" ) == str True >>> type( 0 ) == int True >>> class Test1 ( object ): pass >>> class Test2 ( Test1 ): pass >>> a = Test1() >>> b = Test2() >>> type( a ) == Test1 True >>> type( b ) == Test2 True >>> type( b ) == Test1 False >>> isinstance( b, Test1 ) True >>> isinstance( b, Test2 ) True >>> isinstance( a, Test1 ) True >>> isinstance( a, Test2 ) False >>> isinstance( [], list ) True >>> isinstance( {}, dict ) True
>>> a = [] >>> type(a) <type 'list'> >>> f = () >>> type(f) <type 'tuple'>
DB_URL = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format( USERNAME, PASSWORD, HOST_NAME, PORT, DB_NAME )
>>> b = str.encode(y) >>> type(b) >>> b b’Hello World!’ To alter from bytes to str, capitalize on bytes.decode(). >>> z = b”Hello World!” >>> y = “Hello World!” >>> type(z) >>> type(y) To alter from str to bytes, capitalize on str.encode(). >>> a = bytes.decode(z) >>> type(a) >>> a ‘Hello World!’ # to utf-8 'BG7NYT'.encode('utf-8') # to utf-16 'BG7NYT'.encode('utf-16')
strHello = "the length of (%s) is %d" %('Hello World',len('Hello World')) print strHello
前导字符串加0
for i in range(5): print("%03d" % i) for i in range(100): print('{0:0>3d}'.format(i))
text = "Hello" print(f"{text:-^15}") number = 1 print(f"{number:0<5}") print(f"{number:0>5}")
-----Hello----- 10000 00001
打印99乘法表
for i in range(1,10): for j in range(1,i+1): print(f"{j}*{i}={j*i}",end=" ") print("")
1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=9 1*4=4 2*4=8 3*4=12 4*4=16 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
格式化日期
>>> from datetime import * >>> a = date.today() >>> a datetime.date(2023, 9, 2) >>> f"{a:%Y-%m-%d}" '2023-09-02'
import re prompt='给我画一张 An octopus catches crabs in the sea 3D' string=re.sub('[\u4e00-\u9fa5]', '', prompt) print(string)
simple_punctuation = '[’!"#$%&\'()*+,-/:;<=>?@[\\]^_`{|}~,。,]' line = re.sub(simple_punctuation, '', string)
import uuid # 生成一个基于时间和主机地址的UUID uuid1 = uuid.uuid1() # 生成一个基于命名空间和名字的MD5散列的UUID uuid3 = uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') # 生成一个随机UUID uuid4 = uuid.uuid4() # 生成一个基于命名空间和名字的SHA-1散列的UUID uuid5 = uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') # 打印UUID的字符串表示形式 print(str(uuid1)) print(str(uuid3)) print(str(uuid4)) print(str(uuid5))
text = "Hello\nWorld\n" lines = text.splitlines() print(lines) # 输出:['Hello', 'World']
text = "\nHello, World!\n" new_text = text.strip("\n") print(new_text) # 输出:Hello, World! text = "Hello, World!\n" new_text = text.rstrip("\n") print(new_text) # 输出:Hello, World!
import emoji result = emoji.emojize('Python is :thumbs_up:') print(result) # 'Python is ' <br/># You can also reverse this: result = emoji.demojize('Python is ') print(result)<br/># 'Python is :thumbs_up:'
str = "hello world" print(str.title()) # 输出: 'Hello World'
import string str = "hello world" print(string.capwords(str)) # 输出: 'Hello World'
str.startswith(str, beg=0,end=len(string))
#!/usr/bin/python str = "this is string example....wow!!!"; print str.startswith( 'this' ); print str.startswith( 'is', 2, 4 ); print str.startswith( 'this', 2, 4 );
str.endswith(suffix[, start[, end]])
#!/usr/bin/python str = "this is string example....wow!!!"; suffix = "wow!!!"; print str.endswith(suffix); print str.endswith(suffix,20); suffix = "is"; print str.endswith(suffix, 2, 4); print str.endswith(suffix, 2, 6);
for i in [12.12300, 12.00, 200.12000, 200.0]: print('{:g}'.format(i))
f = 3.1415926 print('%.2f'%f) print('%.3f'%f) print('%.4f'%f) print('{:.2f}'.format(f)) print('{:.3f}'.format(f)) print('{:.4f}'.format(f))
colours = ["RED","GREEN","BLUE"] for colour in colours: print colour
colours = ["RED","GREEN","BLUE"] for i in range(0, len(colours)): print i, colour[i]
当前日期
import time dt = time.strftime('%Y-%m-%d.%X',time.localtime(time.time())) print(dt)
>>> import time >>> dt = time.strftime('%Y-%m-%d.%X',time.localtime(time.time())) >>> print(dt) 2014-01-23.11:07:28
from datetime import datetime print(datetime.today()) print(datetime.now()) print(datetime.now().date()) print(datetime.now().time())
2023-03-11 18:30:34.657155 2023-03-11 18:30:34.657176 2023-03-11 18:30:34.657182
today = datetime.today() yesterday = (today - timedelta(days=1)).date()
from datetime import datetime datetime.today().strftime('%Y-%m-%d.%H:%M:%S') timepoint = time.strftime('%Y-%m-%d.%H:%M:%S',time.localtime(time.time()))
from datetime import datetime dt_str = '27/10/20 05:23:20' dt_obj = datetime.strptime(dt_str, '%d/%m/%y %H:%M:%S') print("The type of the date is now", type(dt_obj)) print("The date is", dt_obj)
from datetime import datetime begin='2023-02-01' end='2023-02-28' interval=datetime.strptime(end,'%Y-%m-%d').date() - datetime.strptime(begin,'%Y-%m-%d').date() print(interval.days)
from datetime import timedelta,datetime now = datetime.now() # 获取昨天日期: yesterday = now - timedelta(days=1) # 获取明天日期: tomorrow = now + timedelta(days=1)
# 获取本周第一天和最后一天: this_week_start = now - timedelta(days=now.weekday()) this_week_end = now + timedelta(days=6-now.weekday()) # 获取上周第一天和最后一天: last_week_start = now - timedelta(days=now.weekday()+7) last_week_end = now - timedelta(days=now.weekday()+1) # 获取上月第一天和最后一天: last_month_end = this_month_start - timedelta(days=1) last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1) # 获取本季第一天和最后一天: month = (now.month - 1) - (now.month - 1) % 3 + 1 this_quarter_start = datetime.datetime(now.year, month, 1) this_quarter_end = datetime.datetime(now.year, month, calendar.monthrange(now.year, now.month)[1]) # 获取上季第一天和最后一天: last_quarter_end = this_quarter_start - timedelta(days=1) last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1) # 获取本年第一天和最后一天: this_year_start = datetime.datetime(now.year, 1, 1) this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1) # 获取去年第一天和最后一天: last_year_end = this_year_start - timedelta(days=1) last_year_start = datetime.datetime(last_year_end.year, 1, 1)
计算两个日期之间的月份
import calendar import datetime begin = "2017-11-15" end = "2018-04-23" def monthlist(begin, end): begin = datetime.datetime.strptime(begin, "%Y-%m-%d") end = datetime.datetime.strptime(end, "%Y-%m-%d") result = [] while True: if begin.month == 12: next = begin.replace(year=begin.year+1, month=1, day=1) else: next = begin.replace(month=begin.month+1, day=1) if next > end: break day = calendar.monthrange(begin.year, begin.month)[1] result.append((begin.strftime("%Y-%m-%d"), begin.replace(day=day).strftime("%Y-%m-%d"))) begin = next result.append((begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"))) return result lists = monthlist(begin, end) print(lists) for (b, e) in lists: print(b, e)
import datetime list_time=["2018-05-01","2018-02-01","2018-07-10","2019-06-01"] list_time1=sorted(list_time,key=lambda date:datetime.datetime.strptime(date,"%Y-%m-%d").timestamp()) print('before', list_time) print('after', list_time1) print('before', list_time) print('min', min(list_time1), 'max', max(list_time1))
BOM : fffe BOM_BE : feff BOM_LE : fffe BOM_UTF8 : efbb bf BOM_UTF16 : fffe BOM_UTF16_BE : feff BOM_UTF16_LE : fffe BOM_UTF32 : fffe 0000 BOM_UTF32_BE : 0000 feff BOM_UTF32_LE : fffe 0000