\n 换行

\t 的作用:不仅是 “不换行” , 制表符(缩进)

string.title()    每个单词首字母变大写
upper(), lower()      全部大小
string.strip() 头尾清理干净         =lstrip+rstrip
rev_s = reversed(s) 反转字符串(与列表反转对应起来)
string.split() 分割
string.count(“东西”)

在字符串中出现了多少次,可搭配lower,upper

变成string.lower().count("row")

list.append()   最末尾添加
list.insert(位置,东西) 插入东西
del .list[位置]    删除东西
list.pop(“位置”) 删除东西,并且返回删除的东西
list.remove(值) 

根据值来删除(只删除第一个碰到的)

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets)

while 'cat' in pets:

        pets.remove('cat')

        print(pets)

list.sort()    排序
list.reverse() 倒叙
a =b [:]   (X)  a=b  前者是复制,后者是一起变

                max1 = max("")                   取出最大的

                max_index =  list1.index(max1)

del dic[key] 删除键值对
value = dic.get(key,warning) 如果没有key,那就返回warning
dic.items() 一对都出来        keys,value
dic.keys()  / dic.values() 单独取出来   
set(dic.values()) 找出独一无二的值

字典和列表可以相互嵌套

1.alien_0 = {'color': 'green', 'points': 5} #每个alien有自己的属性

alien_1 = {'color': 'yellow', 'points': 10}

alien_2 = {'color': 'red', 'points': 15} 

aliens = [alien_0, alien_1, alien_2]

for alien in aliens:

        print(alien)

2.favorite_languages = {

                'jen': ['python', 'ruby'],

                'sarah': ['c'],

                'edward': ['ruby', 'go'],

                'phil': ['python', 'haskell'], }

函数内容:

 def describe_pet(pet_name,animal_type = "dog") #默认值直接写在这

function_name(list_name[:]) 用的是列表的副本,不是列表本身

#不知道会传入几个参数

def make_pizza(*toppings):  #   :创建一个名为toppings 的空元组

def build_profile(first, last, **user_info): # ** : 创建一个名为user_info 的空字典

#上面这两个,先满足肯定正常的

user_info例子:

car_dict ={}

def make_car(manufacturer, model, **car_info):

        for key, value in car_info.items():

                car_dict[key] = value # 返回完整的汽车信息字典

        return car_dict

car = make_car('subaru', 'outback', color='blue', tow_package=True)#前两个必备的参数

类Class

#继承

class minicar(car):

        def __init__(self,make,model,year):

                super.__init__(make,model,year)

#私有参数       __name

#类当属性

class Battery:

        def __init__(self, battery_size=75):

                self.battery_size = battery_size

        def describe_battery(self):

                print(f"This car has a {self.battery_size}-kWh battery.")

class ElectricCar:

        def __init__(self, make, model, year):

                self.battery = Battery()

my_tesla = ElectricCar('tesla', 'model s', 2019)

my_tesla.battery.describe_battery()#用内部参数(另外的类)的函数

#随机

from random import randint

randint(1, 6)        #        随机生成1-6之间的数字

players = ['charles', 'martina', 'michael', 'florence', 'eli'] 

first_up = choice(players)        # choice传入列表或元组,随机返回其中一个

#文件     r:读     w:写    a:附加模式(加到最后)    r+:读写模式

with open("name.txt","r",encoding = "utf-8") as f: #不需要考虑安全问题

        lines = f.readlines()  #拿出全部行 在列表中,中间包含\n

        for line in lines:        #对lines循环

                ....

#异常

try-except-else      

try:                

        answer = int(first_number) / int(second_number)

 except ZeroDivisionError:

        print("You can't divide by 0!")

 else:

        print(answer)

#使用json 保存用户生成的数据大有裨益,因为如果不以某种方式存储,用户的信 息会在程序停止运行时丢失

json.dump() 和 json.load()

import json

numbers = [2, 3, 5, 7, 11, 13]

 filename = 'numbers.json'

 with open(filename, 'w') as f:

         json.dump(numbers, f)

 filename = 'numbers.json'

 with open(filename) as f:

         numbers = json.load(f)

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐