字符串:
使用方法修改字符串的大小写:
name = 'ada lovalace' print("首字母大写:",name.title()) print("全大写:",name.upper()) print("全小写:",name.lower())
删除空白:
name = ' ada lovalace ' print("删除末尾空白>>"+name.rstrip()+"<<") print("删除开头空白>>"+name.lstrip()+"<<") print("删除两端空白>>"+name.strip()+"<<")
在列表指定位置中插入,删除:
list.insert(位置,值)
name = [' ada lovalace ','LAO','laolao'] print("没插入前:",name) name.insert(1,'花花') print("插入后:",name)
del 列表名[位置]
name = [' ada lovalace ','LAO','laolao'] print("删除前:",name) del name[0] print("删除后:",name)
list.pop()方法
name = [' ada lovalace ','LAO','laolao'] print("删除前:",name) t=name.pop(2) print("删除后:",name) print("删除的值:",t)
list.remove[值]
name = [' ada lovalace ','LAO','laolao'] print("删除前:",name) name.remove('LAO') print("删除后:",name)
对数字列表执行简单的统计计算:
max(),min(),sum()
dir=[1,2,3,4,5,6,7,8] print("列表的最大值",max(dir)) print("列表的最小值",min(dir)) print("列表求和",sum(dir))
列表解析:
print("列表解析",[i**2 for i in range(10)])
列表复制:
一方改了,另一方没有变化
my_foods = ['pizza','falafel','carrot cake'] friend_foods = my_foods[:] my_foods.append('cannol') friend_foods.append('ice cream') print("My>>",my_foods) print('Friend>>',friend_foods)
函数传参问题:
直接赋值相当于传实参(也就是C中的传指针),函数中的改变会导致主代码中的改变
''' 函数中删除了导致函数外的同事变化 ''' def fucntion(name): while name: print(name.pop()) name = ['叉烧包','蟹黄煎包','红烧排骨','麻婆豆腐'] fucntion(name=name) print(name)
传形参的方式
''' 函数中删除不会导致函数外的同事变化 ''' def fucntion(name): while name: print(name.pop()) name = ['叉烧包','蟹黄煎包','红烧排骨','麻婆豆腐'] fucntion(name=name[:]) print(name)
传递任意数量的实参,在函数中保存形式是元组
def fucntion(*name): print(name) name = ['叉烧包','麻婆豆腐'] fucntion(name,name,name)
使用任意数量的关键字实参,也就是后面的任意数量的参数有带等号的,传过去的形式是字典
def build_profile(first, last, **usr_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key,value in usr_info.items(): profile[key]=value return profile usr_profile = build_profile('laolao','一朵菊花脸上遮',location='ZheJiang',是否去过武汉='没') print(usr_profile)
类:
值的修改
class Dog(): def __init__(self, name, age): self.name = name self.age = age def sit(self): print(self.name.title() + "is setting") def roll_over(self): print(self.name+"is "+str(self.age)+" years old") ''' 类中值修改方式一 ''' self.age+=1 a = Dog(name='laolao',age=2) print(a.name.title()) print(a.age) ''' 类中值修改方式二 ''' a.age+=1 a.roll_over() a.roll_over()
继承
class Car(): ''' 父类 ''' def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0; def get_descriptive_name(self): long_name = str(self.year)+" "+self.make + " " +self.model return long_name.title() def read_odometer(self): print("This car has" + str(self.odometer_reading) + "miles on it.") def update_odometer(self,milage): if milage >= self.odometer_reading: self.odometer_reading=milage else: print("You can't roll back an odometer!") def increment_odometer(self,miles): self.odometer_reading+=miles class ElectricCar(Car): ''' 子类(父类) ''' def __init__(self,make,model,year): super().__init__(make,model,year) my_tesla = ElectricCar('tesla','model s',2020) print(my_tesla.get_descriptive_name())
文件:
replace(),可以实现指定内容的替换
str = '我喜欢吃香蕉' print(str.replace('香蕉','葱油鸡'))
用json.dump([文件内容],[句柄])想一个JSON格式的文件中写入内容
import json num=[] for i in range(5): num.append(i) ''' 自定义一下文件名,后缀指定为JSON ''' filname='1.json' with open(filname,'w') as f: json.dump(num,f)
用 json.load([文件句柄])读取JSON格式的文件,如果这个文件中包含中文,在open里面加上 encoding='utf-8'
import json filname='1.json' with open(filname,'r',encoding='utf-8') as f: print(json.load(f))
测试代码:
断言:self.assertEqual(formatted_name,'Janis Joplin')
import unittest def get_fromatted_name(s,b): return s.title()+' '+b.title() class NamesTestCase(unittest.TestCase): def test_first_last_name(self): formatted_name = get_fromatted_name('janis','joplin') self.assertEqual(formatted_name,'Janis Joplin') unittest.main()
Django3初体验:
一些代码与网页页面之间的对应关系——model.py
Meta类可以更改模型名称
外联指定了Pizza类,就可在Topping类中修改Pizza类的内容【旁边的绿色加号和黄色的铅笔】
类中定义的变量对应网页上的标签
PS:更改后需要重新迁移一遍
python manage.py makemigrations pizzas python manage.py migrate
一些代码与网页页面之间的对应关系——项目:
网页创建:
由于我的Django是3而书上的的是1所以还是遇到了一些坑点,特此记录一下
1.映射URL:编辑项目主文件learning_log的urls.py
"""learning_log URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.urls import path, include ''' from django.contrib import admin: 导入 Admin 功能模块。 from django.urls import path,include: 导入 URL 编写模块。 urlpattems: 整个项目 的 URL 集合,每个元素代表一条 URL 信息。 ''' urlpatterns = [ path('admin/', admin.site.urls),# admin.site. urls 是 URL 的处理函数,也称为视图函数。 # path('', include('learning_logs.urls')), path('',include(('learning_logs.urls'),namespace='learning_logs')), # URL 为空,代表为网站的域名, 即127.0.0.1:8000, 通常是网站的首页 ; include 将该 URL 分发给learning_logs的 urls.py 处理 # namespace 用来把learning_logs项目的URL和其他项目的区分开(也就是说告诉Django这里用的是learning_logs的url.py文件) ]
2.在项目learning_logs中新建一个urls.py,并编写他:
'''定义learning_logs的URL模块''' from django.conf.urls import url from django.urls import path from . import views app_name='learning_logs' urlpatterns = [ # 主页 path('',views.index,name='index'), # url('',views.index,name='index'), ]
3.编写视图,修改learning_logs文件中的view.py
from django.shortcuts import render # Create your views here. def index(request): '''学习笔记的主页''' return render(request,'learning_logs/index.html')
4.编写模板,创建template->learning_logs->index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Learning Log</title> </head> <body> <p>Learing Log</p> <p>Learing Log helps you keep track of your learning,for any topic you're learning about.</p> </body> </html>
5.开启服务器大功告成:
python manage.py runserver
这里记录一些注意点:
- 报错:'Specifying a namespace in include() without providing an app_name '
- 记得加',':
- 报错:TypeError: __str__ returned non-string (type NoneType)
- 原因:models.DateTimeField不能做str的参数
显示所有主题页面
这里要理清楚一个问题:数据库中的值到底是怎么传送给网页的
'''views.py'''' from django.shortcuts import render from .models import Plan,日期 # Create your views here. def index(request): return render(request,'规划1/index.html') def topics(request): '''显示所有的主题''' topics = Plan.objects.order_by('edit_data') ''' 查询数据库中的Plan项,并把所有的内容按照‘edit_data’排序,然后保存在topics中 ''' context = { '内容' : topics } ''' 生产一个键值对,键是我们将在模版中用来访问数据的名称【重点注意!!!】,值是我们要发送给模版的数据 ''' return render(request, '规划1/topics.html', context)