PythonQuickView
處理字符串
#對(duì)格式的處理
text = "This is a text."
print(text.title()) #以首字母大寫的方式顯示每個(gè)單詞
print(text.upper()) #將字符串轉(zhuǎn)換為大寫
print(text.lower()) #將字符串轉(zhuǎn)換為小寫
#Python可以使用加法直接拼接字符串
a = "This "
b = "is"
c = " a test."
print(a + b + c)
#Python中的轉(zhuǎn)義符
print("\theyyy") #制表符栗菜,即四個(gè)空格
print("Hey\nMy name is Jokey\n") #換行符
print("Languages:\n\tPython\nC\nJavascript") #組合使用
#刪除空白
text = " You can see dat spaces "
text.rstrip() #刪除末尾的空格
text.lstrip() #刪除開頭的空白
text.strip() #刪除兩邊的空白
#使用print輸出字符串和數(shù)字組合時(shí)應(yīng)使用str()將數(shù)字轉(zhuǎn)換為字符串
age = 23
print("My age is " + str(age))
列表
motocycles = ['honda','yamaha','suzuki']
#訪問列表元素
print(motocycles[0])
print(motocycles[-1])
print(motocycles[0].title())
#更改元素
motocycles[1] = 'ducati'
motocycles.append('ducati') #在列表末尾添加元素
motocycles.insert(0,'ducati') #在指定位置添加元素
del motocycles[2] #刪除指定位置元素
popped_motocycle = motocycles.pop() #彈出列表最后一個(gè)元素赖条,將其值付給pop_motocycle
popped_motocycle = motocycles.pop(0) #彈出列表指定元素,并賦值
#列表排序
motocycles.sort() #將元素按字母順序排序(永久改變)
print(sorted(motocycles)) #臨時(shí)排序
motocycles.reverse() #反轉(zhuǎn)列表原順序
len(motocycles) #確定列表長度
#切片(可用for遍歷)
print(motocycles[0:3]) #打印前三個(gè)元素
print(motocycles[:3])
print(motocycles[2:])
#復(fù)制列表
new_list = motocycles[:] #復(fù)制整個(gè)列表
數(shù)字相關(guān)
#使用range函數(shù)遍歷數(shù)字
for value in range(1,5): #生成數(shù)字1~4
print(value)
#生成數(shù)字列表并處理
numbers = list(range(1,6))
結(jié)果: [1,2,3,4,5]
numbers = list(range(2,11,2)) #從2開始數(shù)顶别,到11停止,步長為2
結(jié)果: [2,4,6,8,10]
digits = [1,2,3,4,5,6,7]
min(digits) #找最小值
max(digits) #找最大值
sum(digits) #求總和
#列表解析
squares = [value**2 for vaule in range(1,11)] #求平方數(shù)列
print(squares)
#對(duì)輸入的字符串轉(zhuǎn)換為數(shù)字類型
int(age) #轉(zhuǎn)換為整數(shù)
float(age) #轉(zhuǎn)換為浮點(diǎn)數(shù)
元組
dimensions = (200,50)
print(dimensions[0])
#若要修改元組龟劲,需重新為元組賦值梢薪,例如:
dimensions = (100,200,50)
Python中的邏輯運(yùn)算
#基本邏輯運(yùn)算
if 'cat' == 'CAT'
if 'cat' != 'Cat'
if 18 <= 20
if 18 <= 20 and 'ac' == 'Cat'
if 18 <= 20 or 1 == 2
#檢查特定值是否在列表中
animals = ['cat','dog','banana']
if 'cat' in 'banana':
print("yes")
#布爾表達(dá)式
true_flag = True
false_flag = False
Python中的If結(jié)構(gòu)
age = 12
if age == 12:
print(age)
elif age < 12:
print(age)
else:
print(age)
字典
alien = {
'color':'black',
'points':5,
'age':1200,
}
print(alien['color'])
alien['length'] = 80 #添加鍵值對(duì)
alien['color'] = 'yellow' #修改字典中的value
del alien['points'] #刪除鍵值對(duì)
#遍歷鍵值對(duì)
for key,value in alien.items():
print(key + '\n')
print(value)
#遍歷key
for key in alien.keys():
print(key)
for key in sorted(alien.keys()): #按順序遍歷字典中的所有key
print(key)
#遍歷value
for value in alien.values():
print(value)
用戶輸入
message = input("Enter ur message: ")
print(message) #用戶輸入默認(rèn)為字符串格式,如需解讀為數(shù)字宇姚,使用print(int(age))
函數(shù)
#定義函數(shù):
def greet_user(username): #注意最后的冒號(hào)
print("Hello!" + username.title())
greet_user('Nick')
greet_user(username='Nick') #關(guān)鍵字實(shí)參,注意參數(shù)傳遞時(shí)不要空格
def describe_pet(pet_name,animal_type='cat'): #默認(rèn)值
print('Some stuff....')
return pet_name.title()
describe_pet(pet_name='Flipper')
#傳遞任意數(shù)量的實(shí)參
def make_pizza(*toppings): #形參前的星號(hào)表明不知道要傳入多少實(shí)參匈庭,故創(chuàng)建一個(gè)元組用來保存實(shí)參
print(toppings)
模塊
#導(dǎo)入模塊
import pizza #導(dǎo)入pizza.py整個(gè)模塊
pizza.make_pizza('Potato') #調(diào)用pizza模塊中的make_pizza函數(shù)
#導(dǎo)入特定的模塊
from module_name import function_name
make_pizza('Tomato') #直接調(diào)用函數(shù),無需寫明模塊名
#使用as為函數(shù)指定別名
from pizza import make_pizza as mp #為make_pizza函數(shù)添加別名mp
mp('Tomato')
#使用as給模塊指定別名
import pizza as p #為pizza模塊添加別名p
p.make_pizza('banana')
#導(dǎo)入模塊中的所有函數(shù)
from pizza import * #導(dǎo)入模塊中的所有函數(shù)
make_pizza('Peach')
類
#創(chuàng)建類
class Dog(): #注意冒號(hào)
def __init__(self,name,age): #__init__是一個(gè)特殊的方法
self.name = name #類的屬性
self.age = age
def sit(self):
print(self.name.title() + " is now sitting.")
#創(chuàng)建實(shí)例
my_dog = Dog(2,'Cattie')
print(my_dog.name)
my_dog.sit() #調(diào)用方法
#更新屬性
class Dog():
def __init__(self,name,age):
self.name = name
self.age = age
self.stuff = 0
def update_stuff(self,stuff_value): #添加用來更新屬性的方法
self.stuff = stuff_value
new_dog = Dog('Buff',3)
new_dog.update_stuff(23)
繼承
class HashCat(Dog): #繼承父類Dog
def __init(self,name,age):
super().__init__(name,age) #super()是特殊函數(shù)浑劳,幫助python將子類和父類關(guān)聯(lián)起來
self.max_hash = 70
def describe_battery(self): #添加子類特有的屬性和方法
print("This cat has a " + str(self.max_hash) )
my_hashCat = HashCat('cattie',20)
my_hashCat.describe_battery()
導(dǎo)入類
from animal import Dog,HashCat
#例如導(dǎo)入模塊random并生成隨機(jī)數(shù)
from random import randit
x = randit(1,6) #返回一個(gè)指定范圍內(nèi)的整數(shù)(1~6)
文件處理
#打開文件
with open('text_files\123.txt') as file_object: #打開text_files文件夾內(nèi)的123.txt
contents = file_object.read()
print(contents)
path = 'rC:\Users\text_files\filename.txt'
with open(path) as file_object:
for line in file_object: #逐行讀取
print(line)
#創(chuàng)建一個(gè)包含文件各行內(nèi)容的列表
with open(filename) as f:
lines = f.readlines()
for line in lines:
print(line)
#替換指定的單詞
message = 'i really like dogs.'
message.replace('dogs','cats')
#寫入文件
with open(filename,'w') as f: #'w'寫入模式阱持,'r'讀取模式(默認(rèn)),'r+'能夠讀取和寫入的模式,'a'附加模式
f.write('i love cats')
with open(filename,'a') as f: #'a'不會(huì)在打開文件時(shí)清空文件魔熏,而將內(nèi)容都添加到文件末尾衷咽,如果文件不存在,則創(chuàng)建一個(gè)新的
f.write('This is a column added')
異常
try:
print(5/0) #執(zhí)行try中的語句蒜绽,若出現(xiàn)錯(cuò)誤镶骗,執(zhí)行except,若無錯(cuò)誤躲雅,執(zhí)行else
except:
print('fail') #若需要失敗時(shí)一聲不吭鼎姊,則此處為pass
else:
print('success')