Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

1.5. 数据类型

1.5.1. type 数据类型检测

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'>
		
		

1.5.2. 字符串

1.5.2.1. String function

str.find()

找到字符,返回字符串位置。没有找到返回 -1

"aaa bbb ccc".find('aaa')
				
str.find()

查找并替换字符串

a = 'hello word'
a.replace('word','python')
				
format 方法
			
DB_URL = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(
    USERNAME, PASSWORD, HOST_NAME, PORT, DB_NAME
)			
			
				
格式化字典输出
				
member = {'name':'neo','age':18}
'my name is {name},age is {age}'.format(**member)        #**dict				
				
					

输出

				
>>> member = {'name':'neo','age':18}
>>> 'my name is {name},age is {age}'.format(**member) 
'my name is neo,age is 18'				
				
					
Convert str to bytes in python
			
>>> 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')
			
				

1.5.2.2. % 字符串格式化输出

			
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))    		
			
			

1.5.2.3. f-string 格式化字符串

			
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'			
			
			

1.5.2.4. 去除中文

			
import re
prompt='给我画一张 An octopus catches crabs in the sea 3D'
string=re.sub('[\u4e00-\u9fa5]', '', prompt)
print(string)			
			
			

1.5.2.5. 去除标点符号

			
simple_punctuation = '[’!"#$%&\'()*+,-/:;<=>?@[\\]^_`{|}~,。,]'
line = re.sub(simple_punctuation, '', string)			
			
			

1.5.2.6. 去除数字

			
re.sub("[0-9]", " ", line)			
			
			

1.5.3. float 浮点数值

		
for i in [12.12300, 12.00, 200.12000, 200.0]:
    print('{:g}'.format(i))		
		
		

1.5.4. Array

1.5.4.1. 遍历数字

			
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]			
			
			

1.5.4.2. split / join

			
>>> str = 'a|b|c|d|e'
>>> str.split("|")
['a', 'b', 'c', 'd', 'e']

>>> list = ['a', 'b', 'c', 'd', 'e']
>>> "|".join(list)
'a|b|c|d|e'
			
			

1.5.5. 日期和时间

1.5.5.1. 当前时间

当前日期

			
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()			
			
			

1.5.5.2. 生成时间

			
from datetime import date
print(date(2002, 12, 31))			
			
			

1.5.5.3. 日期格式化

			
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()))
			
			

1.5.5.4. 字符串转日期

			
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)			
			
			

1.5.5.5. 日期转字符串

			
from datetime import date
print(date(2002, 12, 31).strftime('%Y-%m-%d'))			
			
			

1.5.5.6. 日期运算

天数差
				
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) 
			
				

1.5.5.7. 日期范围计算

计算两个日期之间的月份

			
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)
			
			
			

1.5.5.8. 日期排序

			
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))			
			
			

1.5.6. bytes 类型

1.5.6.1. bytes to string

			
.decode()
			
			

1.5.6.2. BOM头

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
			

1.5.6.3. replace

bytes类型的数据,替换方法,不要忘记b""

			
a = b"abc"
b = a.replace(b"a", b"f")
print(b)
			
			

1.5.6.4. pack/unpack