Python学习笔记1

    xiaoxiao2021-04-18  70

    #1.变量和简单数据类型 print("hello python world!") message = "hello python world!" print(message) print(message.title()) #首字母大写 print(message.uper())  #全部大写 print(message.lower()) #全部小写 full_name = "lin" + "hai" #合并字符串 print("Hello, " + full_name.title() + "!") print("John Q. %s10s" % ("Man","Public")) #%是针对字符串的格式说明符,10表示长度为10的字符,如果长度小于10则该字符串前会加入相应数量空格 print("\tPython") #制表符 print("Languages:\nPython\nC\nJavaScript") type(12j+1) #序数尾部都有一个字母j name = "lin hai " name.rstrip() #删除末尾空白 name.lstrip() #删除开头空白 name.strip()  #删除两端空白 age = 23 message = "Happy" + str(age) + "rd Birthday!" #str()将整数用作字符串 print(message) #2.列表 shapes = ['a', 'b','c','d','e'] print(shapes[0])             #打印第1个元素 print(shapes[1].title())     #打印第2个元素,且首字母大写 print(shapes[-1])            #打印最后一个元素 print(shapes[-2])            #打印倒数第二个元素 shapes.append('granda') #添加元素 print(shapes) e = [] e.append("e1")#添加元素 e.append("e2") e.extend("e3","e4","e5") #同时添加多个元素   shapes.insert(0,"bb") #在第1个位置插入元素 print(shapes) del shapes[0] #删除第一个元素 print(shapes) poped_shapes = shapes.pop() #删除列表末尾的元素 print(shapes) print(poped_shapes) first_shapes = shapes.pop(0) #删除第1个元素 shapes.remove("e") #删除e, 但remove只删除第1个指定的值 print(shapes) cars = ['bmw','audi','bench','toyota','subaru'] cars.sort() #永久性排序 print(cars)  cars.sort(reverse = True) #逆序 print(cars) print(sorted(cars)) #临时排序 print(cars) cars.reverse() #永久性地反转列表元素的排列顺序 len(cars) #列表的长度 for car in cars: print(car) for value in range(1,6): #打印1-5 print(value) numbers = list(range(1,6)) print(numbers) min(numbers) max(numbers) sum(numbers) squares = [value**2 for value in range(1,11)] #1到10的平方 print(squares) print(squares[0:3]) #打印0,1,2的元素 print(squares[:4])  #打印0,1,2,3的元素 print(squares[2:])  #打印从第3个元素开始到末尾的所有元素 print(squares[-3:]) #打印最后三个元素 for value in squares[:3]: print(value) squares1 = squares[:] #复制列表 print(squares1) squares2 = squares #是将副本存储到squares2中,因此二者指向同一个列表 #元组:不可变的列表 dimensions = (200,50) #定义元组,使用的是圆括号而不是方括号 print(dimensions[0]) #dimensions[1] = 10   #试图修改元组是被禁止的 #3.if语句 #例1 for car in cars: if car == 'bmw': print(car.upper()) else:  print(car.lower()) car = 'Audi' car == 'audi' #返回的是False,区分大小写 car.lower() == 'audi' if car !="audi" : print("car is title") age = 19 age <= 21 and age >= 15 age <20 or age >19  car = 'bench' car in cars     #检查特定值是否包含在列表中 car not in cars #检查特定值是否不包含在列表中 #例2 if age < 18: print("You are so young!") else if age < 25: print("You are young!") else: print("Hello uncle!") #例3 requested_toppings = [] if requested_toppings: #确定列表非空 for requested_topping in requested_toppings: print("Adding" + requested_topping + ".") print("\nFinished making your pizza") else: print("Are you sure you want a plain pizza?") #4.字典 alient = {'color':'green','points':5} #颜色键值对和点数键值对 print(alient['color']) print(alient['points']) alient['x_position'] = 0  #新增键值对 alient['y_position'] = 25  print(alient) alient['color'] = 'yellow' #修改字典中的值 del alient['points'] #删除键值对 alient1 = {} #创建空字典 alient1['color'] = 'green' alient1['points'] = 5 #例1 user = {'username':'hy','first':'huang','last':'ying'} for key,value in user.items(): #遍历键值对 print("\nkey:" + key) print("value:" + value) for item in user.keys():       #遍历键 print(item.upper()) for item in sorted(user.keys()): print(item.upper()) for name in user.values():     #遍历值 print(name.title()) for name in set(user.values()):#用集合,使得每个元素独一无二 print(name.title()) #例2 alient_0 = {'color':'green','points':5} alient_1 = {'color':'red','points':10} alient_2 = {'color':'yellow','points':15} alients = [alient_0, alient_1, alient_2]  #字典列表 for alient in alients: print(alient) alients = [] for alient_number in range(30):   new_alient = {'color':'green','points':alient_number} alients.append(new_alient) for alient in alients[:5]:  #显示前五个 print(alient) print("...") print("Total number of alients:" + str(len(alients))) #例3 pizza = {'crust':'thick', 'toppings':['mushrooms','extra cheese']} #字典中存储列表 for topping in pizza['toppings']: print("\t" + topping) #例4 favorate_languages = {                       'jen':['python','ruby'],                       'sarah':['c'],                       'edward':['ruby','go'],                       'phil':['python','haskell'],             } for name,languages in favorate_languages.items(): print("\n" + name.title() + "'s favorate languages are:") for language in languages: print("\t" + language.title()) #例5 users = {         'aeinstein':{            'first':'albert', 'last':'einstein', 'location':'princeton',            }, 'mcurie':{        'first':'marie', 'last':'curie', 'location':'paris',        },         } for username,user_info in users.items(): print("\nUsername:" + username) full_name = user_info['first'] + user_info['last'] location = user_info['location'] print("\tFullname" + full_name.title()) print("\tLocation:" + location.title()) #5.用户输入和while循环 message  = input("Tell me something, and I will repeat it back to you:") print(message) age = input("How old are you?") #默认解读为字符串 age = int(age) #使用int()将数字的字符串转换为数值 age >= 18 number = input("Enter a number, and I'll tell you if it's even or odd:") number = int(number) if number % 2 == 0: print("\nThe number" + str(number) + "is even.") else: print("\nThe number" + str(number) + "is odd.") #例1 current_number = 1 while current_number <=5: print("current_number") current_number +=1 if current_number == 3: break #例2 number = 0 while number < 10:.0. number +=1 if number % 2 ==0: continue print(number) #例3 unconfimed_users = ['alice','brian','candace'] confirmed_users = [] while unconfirmed_users: current_user = unconfimed_users.pop() #删除列表末尾的元素 print("Verifying user:" + current_user.title()) confirmed_users.append(current_user) print("\nThe following users have been confirmed:") for confirmed_user in confirmed_users: print(confirmed_user.title()) #简单匿名函数lambda,filter filter_me = [1,2,3,4,5,6,7,8] result = filter(lambda x: x%2==0,filter_me) print(*result) #短路循环:Map map_me = ['a','b','c','d','e','f','g'] result1 = map(lambda x:"The letter is %s \n"%x,map_me) print(*result1) #列表解析 all = [1,2,3,4,5,6,7,8,9,10] print([x for x in all if x%2==0]) #例4 pets = ['dog','cat','dog','rabbit','dog'] while 'dog' in pets: pets.remove('dog') #正则表达式 #1. 打印以hy开头的字符 str1 = ['hy haha', 'love haha', 'hymain'] for stri in str1:     if stri.startswith('hy'):         print(stri) #2. 打印以hy开头和结尾的字符 str2 = ['hyhahahy', 'hyhaha', 'hahahy', 'hahahyhaha'] for stri in str2:     if stri.startswith('hy') and stri.endswith('hy'):         print(stri) #3. 判断一个变量名是否以下划线或者字母开头 a1 = 'Hhy' a2 = '1xhy' a3 = '_hy' def judge(a):     if a[0]=='_' or 'A'<=a[0]<='z':         print('合法命名')     else:         print('非法命名')     return 0; judge(a1) judge(a2) judge(a3) # 可以看到,每次匹配都要单独完成,可将其做成一个规则:正则表达式 # 正则表达式:使用单个字符串来描述匹配一系列符合某个句法规则的字符串;是对字符串操作的一种逻辑公式 # 匹配过程:一次拿出表达式和文本中的字符比较,若每个字符都能匹配,则匹配成功。 # import re:python正则表达式模块 # 步骤:先用re.compile()生成pattern对象->再用pattern的匹配方法匹配出结果字符串 #1.1 例1的正则方法  import re str3 = 'hy love XLh' pattern = re.compile(r'hy',re.I)  #r是为了避免\为转义符,re.I是忽视大小写 mastr = pattern.match(str3) mastr.group() mastr.span() mastr.string # 正则表达式语法 .     :匹配任意字符(除了\n) []    :匹配字符集 \d或\D:匹配数字或非数字 \s或\S:匹配空白或非空白 \w或\W:匹配单词字符[a-zA-Z0-9]h或非单词字符 *        :匹配前一个字符0次或无限次 +        :匹配前一个字符1次或无限次 ?        :匹配前一个字符0次或一次 {m}或{m,n}:匹配前一个字符m次或m到n次 *?或者+?或者?? :匹配模式变为非贪婪(尽可能少匹配字符) ^     :匹配字符串开头 $     :匹配字符串结尾 \A或\Z:指定的字符串必须出现在开头或结尾 |         :匹配左右任意表达式 (ab)      :括号中表达式作为一个分组 \<number> :引用编号为number的分组匹配到的字符串 (?P(name)):分组起一个别名 (?P=name) :引用别名为name的分组匹配字符串 re.match(r'^[\w]{4,10}@163.com$','imooc@163.com')  # 匹配以@163.com结尾且长度为4到10的字符开头的邮箱 re.match(r'^[\w]{4,10}@(163|126.com)$','imooc@126.com')  # 匹配以@163.com或者@126.com结尾且长度为4到10的字符开头的邮箱 re.match(r'\Aimooc[\w]*','imoocpython')  # 匹配以imooc开头的字符串 re.match(r'[1-9]?\d$|100','99')  # 匹配数字0-100
    转载请注明原文地址: https://ju.6miu.com/read-675216.html

    最新回复(0)