python 基础
来源:互联网 发布:整点抢购软件 编辑:程序博客网 时间:2024/06/05 01:54
# coding=utf-8from math import sqrtfrom string import Templateimport copyif __name__ ==('__main__'): #字符串不可变 stra = 'asdfg "" "" "" """"""As you name' print stra[0] #格式化输出 format = "hello %s i am %d years old" values = ('InAHurry',12) print format % values #另外一种格式化输出的方法 s= Template('$x,you are who') print(s.substitute(x='gjl')) s=Template('${x}om') print (s.substitute(x='m')) s=Template('you are $name,your age is $age') d={} d['name']='gjl' d['age']=12 print (s.substitute(d)) #字符串的方法 #1、寻找子串 并返回最左端索引 print stra.find('name',0,len(stra)) #2、join 将连接序列中的元素 print('-'.join(stra)) #3、lower capitalize print stra.lower(),stra.capitalize() #4、replace print 4,stra.replace('"','') #split print stra.split(" ") #字典dict names = ['gjl','trans','sess','we'] nums=['032','003','134','135'] print nums[names.index('gjl')] #字典可以使用 名字作为键值 nameNum ={ 'gjl':'002', 'trans':'133', 'sess':'134', "we":'135' } print nameNum['gjl'] """x=[] x[42] = "xxx" 会出错 """ x = {} x[42] = "ni shi shui" #下面写一个保存人 电话和 地址信息的数据库 people ={ 'alice':{ 'phonenumber':'012', 'address':'xian' }, 'gjl':{ 'phonenumber': '012', 'address': 'xian' } } def findPeople(): name = raw_input("input your name:") type = raw_input('input what you what to search phone number(p) or address(a)') if people.has_key(name): if type == 'p': print people[name]['phonenumber'] elif type == 'a': print people[name]['address'] else: print 'please input right case' else: print 'no person ' #findPeople() #字典方法之浅拷贝 从下面可以看出 will 和 willer 是俩个对象 但是 will[i] is willer[i] will = ['hello',23,['q','w','e']] willer = copy.copy(will) print id(will) print[id(ele) for ele in will] print id(willer) print [id(ele) for ele in willer] willer[0] = 'hello world' willer[2].append('r') print willer print id(willer) print [id(ele) for ele in willer] print will print id(will) print [id(ele) for ele in will] #上面讲的是列表 其实dict 也是一样的 person = { 'name':'gjl', "address":['121','122'] } chinese =copy.copy(person) chinese['address'].remove('121') #这时候输出person 的值 肯定是被修改过的 print person,chinese #在字典中使用迭代器 如果需要字典的键 keys 和iterkeys it = person.iteritems() for each in it: print 107 ,each print person.keys() print 109,[ele for ele in person.iterkeys()] #利用字典格式化字符串 print('your name is %(name)s you address is %(address)s' % person) #利用 dict 初始化字典 sdict = dict( {'name':'gjl'} ) for each in sdict.iterkeys(): print each
阅读全文