a =3
b =3.14
c =3+4jprint(type(a),type(b),type(c))#結果:<class'int'><class'float'><class'complex'>#判斷變量是否是該類型print(isinstance(a,int))#結果:True
Number實例代碼
import math
print(math.factorial(32))#計算32的階乘263130836933693530167218012160000000print(0.4-0.3==0.1)#實數之間儘量避免直接比較大小Falseprint(0.4-0.3)0.10000000000000003print(math.isclose(0.4-0.3,0.1))#測試兩個實數是否足夠接近True
#python中複數的運算
c =3+4jprint(c+c)#複數相加 print(c.real)#複數的實部print(c.imag)#複數的虛部print(3+4j.imag)#相當於3+(4j).imag#結果:(6+8j)3.04.07.0
text ='''beautiful is better than ugly.
explicit is better than implicit
simple is better than complex
flat is better than nested
'''print(len(text))#字符串長度,即所有字符的數量print(text.count('is'))#字符串中單詞is出現的次數print('beautiful'in text)#測試字符串中是否包含單詞beautiful1214True
字符串操作方法:(以下“str”表示爲一個字符串)
str[ ]:索引
str[ : ]:剪切
len(str):長度
str.upper():字符串中字母大寫
str.lower():字符串中字母小寫
str.capitalize()
str.title()
str.swapcase()
text ='beautiful is better than ugly is.'print(text.upper())#字符串中字母大寫print(text.lower())#字符串中字母小寫print(text.capitalize())#句首字母大寫print(text.title())#每個字符首字母大寫print(text.swapcase())#原來的大寫變小寫,小寫變大寫
BEAUTIFUL IS BETTER THAN UGLY IS.
beautiful is better than ugly is.
Beautiful is better than ugly is.
Beautiful Is Better Than Ugly Is.
BEAUTIFUL IS BETTER THAN UGLY IS.
text ='Beautiful is better than ugly.'print(text.split())#使用空白字符進行分割print(text.split(maxsplit =1))print(text.rsplit(maxsplit =2))print('1,2,3,4'.split(','))print(','.join(['1','2','3','4']))['Beautiful','is','better','than','ugly.']['Beautiful','is better than ugly.']['Beautiful is better','than','ugly.']['1','2','3','4']1,2,3,4
text ='python是一門非常棒的編程語言。'#replace() 方法返回替換後的新字符串,可以直接再次調用replace()方法print(text.replace('棒','優雅').replace('編程','程序設計'))print(text)#text沒有發生變化,是因爲字符串是不可變的,replace()是產生一個新的字符串
python是一門非常優雅的程序設計語言。
python是一門非常棒的編程語言。
for v in str:字符串迭代
index(x):從左到右依次檢測x第一次出現的索引值,如果不存在,返回異常
rindex(x):從右到左依次檢測x第一次出現的索引值,索引值爲從左數的,如果不存在,返回異常
text ='處處飛花飛處處;聲聲笑語笑聲聲。'print(text.rindex('處'))print(text.index('聲'))print(text.count('處'))684
text ='beautiful is better than ugly is.'print(text.startswith('beautiful'))print(text.startswith('Beautiful'))print(text.endswith(('.',',',':')))TrueFalseTrue
strip() 、rstrip()、lstrip():從兩側、右側、左側截取字符串的指定字符
text ='******=======text========###$$$$*****'print(text.strip('*'))#從兩端刪除*號#從兩端刪除=#*,參數中無需規定順序,類似於一個字符串列表。# 右端只刪除了*是因爲參數中沒有$,所以遇到$時候停止print(text.strip('=#*'))print(text.lstrip('*='))#從左端刪除*=#從右端刪除*$=,只刪除了*$,到#停止是因爲參數裏沒有#print(text.rstrip('*$='))
結果:
=======text========###$$$$
text========###$$$$
text========###$$$$***********=======text========###
Process finished with exit code 0
d ={'Michael':95,'Bob':75,'Tracy':85}print(d['Michael'])95
d ={'a':1,'b':2,'b':3}print(d){'a':1,'b':3}
創建字典的另一種方法:dict函數
items =[('name','Ruby'),('age',25)]
d =dict(items)print(d)
d =dict(name ='Ruby',age =25)print(d)#結果:{'name':'Ruby','age':25}{'name':'Ruby','age':25}
字典的常用方法:
copy():返回字典高層結構的一個拷貝,但是不復制嵌入結構,只複製對那些結構的引用。
items =[('name','Ruby'),('age',25),('sex','female')]
d =dict(items)print(d['name'])print(d.get('age','sex'))#如果字典中有age,則返回該鍵相對應的值,如果沒有則返回get函數的第二個參數。#結果:
Ruby
25print(list(d))#返回字典的鍵print(list(d.values()))#返回字典的值print(list(d.items()))#返回字典的所有元素#結果:['name','age','sex']['Ruby',25,'female'][('name','Ruby'),('age',25),('sex','female')]#用for循環,返回字典的所有元素:for k,v in d.items():print(k,v,sep =' ')#結果:
name Ruby
age 25
sex female
'''
字典元素的修改,添加與刪除
'''#當以指定“鍵”爲下標給字典元素賦值時,1)若是“鍵”存在,則修改;2)若是不存在,則添加。
items =[('name','Ruby'),('age',25),('sex','female')]
d =dict(items)
d['name']='zhaojiaxuan'
d['address']='Nei Meng gu 'print(d){'name':'zhaojiaxuan','age':25,'sex':'female','address':'Nei Meng gu '}#用update()方法可以將另一個字典的元素一次性全部添加到當前字典,如果鍵相同就替換,如沒有像關鍵就添加
items =[('name','Ruby'),('age',25),('sex','female')]
d =dict(items)
b ={'name':'zhaojiaxuan','address':'liulin'}
d.update(b)print(d){'name':'zhaojiaxuan','age':25,'sex':'female','address':'liulin'}#刪除
items =[('name','Ruby'),('age',25),('sex','female')]
d =dict(items)print(d.pop('name'))#用pop()刪除指定“鍵”對應的元素,同時返回對應的“值”print(d)
Ruby
{'age':25,'sex':'female'}# 使用popitem()刪除
items =[('name','Ruby'),('age',25),('sex','female')]
d =dict(items)print(d.popitem())#刪除最後一個元素,並以元組的形式返回最後一個元素的鍵值對print(d)('sex','female'){'name':'Ruby','age':25}#使用del函數刪除
items =[('name','Ruby'),('age',25),('sex','female')]
d =dict(items)del d['name']print(d){'age':25,'sex':'female'}
s ={3,5,9,7,6}
s.add(2)#給集合增加一個元素2print(s)
s ={3,5,9,7,6}
d ={8,2,9}
s.update(d)#將集合d更新到集合s中print(s)
s.pop()#隨機刪除一個元素print(s)
s.remove(5)#刪除5print(s)
s.discard(2)#刪除一個不存在的元素,不會報錯print(s)#結果:{2,3,5,6,7,9}{2,3,5,6,7,8,9}{3,5,6,7,8,9}{3,6,7,8,9}{3,6,7,8,9}
綜合示例
list=[1,2,3]tuple=(1,2,3)dict={'a':97,'b':98,'c':88}set={1,2,3}print(dict['a'])#字典的下標是“鍵”,輸出爲對應“鍵”的“值”print(tuple.index(2))#查看元組中元素2首次出現的位置#結果:971#查看字典中那些“鍵”對應的“值”爲98for key,value indict.items():#items爲元素if value ==98:print(key)#結果:
b
map函數
s =[]for i inrange(5):
s.append(i)print(s)
a =map(str,s)#map函數就是把轉換函數,將s中元素從int轉換爲strprint('1'in a)#結果:[0,1,2,3,4]True