Python学习路程day2

时间:2024-11-20 20:33:25

import sys      #接收执行参数

#!/usr/bin/env python

import sys

print (sys.argv)​

例:

>>>python index.py 8000

>>>['index.py','8000']​

字符串常用操作:

移动空白: strip()

分割:split

长度:len(obj)

索引:obj[1]

切片:obj[1:],obj[1:10]

元组里面的元素不可修改

元组里面的元素的元素是可以修改的​

例:

t1 = (1,2,{'k1':'v1'})​

​t1 [2]['k1'] = 2

print (t1)

>>>(1,2,{'k1':2})​

对于Python,一切事物都是对象,对象基于类创建​

Python学习路程day2填写图片摘要(选填)

str内部功能介绍:

#name = "llluo"

#name = str("llluo")                #str类的_init_方法

#print (dir(name))

#print (type(name))

#result = name.__contains__("luo")  #luo是否包含在name中

#result = "luo" in name

#result = name.center(20,'*')       #空20个*号把名字显示在中间

#result = name.capitalize()         #首字母大写

#result = name.count("l")           #找l出现了几次

#result = name.count("l",0,2)       #在0到2之间找有几个l

#result = name.endswith("o")        #是否以o结尾

#result = name.endswith("o",0,4)    #判断0到4之间是不是以o结尾

#result = name.find("u")            #找出"u"在第几个位置,没有则是-1,有多个则显示第一个

#result = name.index("l")           #找出第一个"l"在第几个位置,没有则会报错

#print (result)

#name = "luo {0} as {1}"

#result = name.format("sb","eric")  #字符串格式化

#print (result)

#name = "lll\tuo"

#result = name.expandtabs()         #把\t换成空格

#print (result)

#li = ['a','m','a','z','i','n','g']

#result = "_".join(li)              #以下划线连接字符,没有则是空

#print (result)

#name = "luoisstar"

#result = name.partition("is")      #以is为分割点

#print (result)

#name = "luoisstar"

#result = name.replace("s","d",1)   #把s都替换成d,后面加了参数,就会转换几个

#print (result)

字典:

dic = {'k1':'v1','k2':'v2'}

​dic.get('k1')

dic.get('k2')

dic.get('k3')         #因为没有k3,所以返回值为None

dic.get('k3','v3')   #​如果没有k3,则会生成对应值v3,如果原来k3有值,则会返回原值

​​dic.keys()             #返回键

dic.values()          #返回值

​dic.items()            #返回键值对

​dic.pop('k1')         #删掉一个键值

dic.popitem()       #​随机删除一个键值

dic.​setdefault('k4',123)   #设置默认值,不写则为none

dic.update({'k5':123})      #生成一个新dic字典,原字典删除

例:把列表中大于44的和小于44的数加到字典。​有两种方法,请参考

​#!/usr/bin/env python

# -*- coding:utf-8 -*-

#Author:luo lingfeng

dic = {}

l1 = []

l2 = []

shu = [1,3,4,5,6,33,22,44,55,99,12,34,54,65,76]

for i in shu:

if i > 44:

l1.append(i)

else:

l2.append(i)

dic['k1'] = l1

dic['k2'] = l2

print dic

事例二:​

#!/usr/bin/env python

# -*- coding:utf-8 -*-

#Author:luo lingfeng

dic = {}

shu = [1,3,4,5,6,33,22,44,55,99,12,34,54,65,76]

for i in shu:

if i > 44:

if "k1" in dic.keys():

dic["k1"].append(i)

else:

dic["k1"] = [i,]

else:

if "k2" in dic.keys():

dic["k2"].append(i)

else:

dic["k2"] = [i,]

print dic