python3 认真学习的第四天,从零开始

>>> s2='today is {week},the temperature is {degree} degrees.'
>>> s2.format(week='sunday',degree=22)
'today is sunday,the temperature is 22 degrees.'
>>> s2.format(degree=22,week='sunday')
'today is sunday,the temperature is 22 degrees.'
>>> s3='today is {week} ,{},the {} temperatuer is {degree} degrees'
>>> s3.format(23333,'bilibili',week='sunday',degree='22')
'today is sunday ,23333,the bilibili temperatuer is 22 degrees'
>>> s3.format(week='sunday','bilibili',233333,degree='22')#format前面应是按顺序格式化参数值,
  File "<stdin>", line 1#后面应是按关键字格式化,否则会抛出异常
SyntaxError: positional argument follows keyword argument
>>> s4='today is {week} ,{1},the {0} temperatuer is {degree} degrees'#0表示第一个参数,1表示第二个参数
>>> s4.format(23333,'bilibili',week='sunday',degree='22')
'today is sunday ,bilibili,the 23333 temperatuer is 22 degrees'
>>> fullname=['song','wang']
>>> 'Mr {name[1]}'.format(name=fullname)#{name[1]}获取fullname列表中的第二个值
'Mr wang'

import math
s5='the {mod.__name__} modile defines the value {mod.pi} for PI'
print(s5.format(mod = math ))

>>> '{coll!s} {coll!r} {coll!a}'.format(coll='中')
"中 '中' '\\u4e2d'"

>>> '整数:{num} 浮点数:{num:f}'.format(num=21)
'整数:21 浮点数:21.000000'
>>> '十进制:{num} 二进制:{num:b} 八进制:{num:o} 十六进制:{num:x}'.format(num=100)
'十进制:100 二进制:1100100 八进制:144 十六进制:64'

>>> '科学计数法:{num:e}'.format(num=60)
'科学计数法:6.000000e+01'
>>> '百分之计数:{num:%}'.format(num=100)
'百分之计数:10000.000000%'
>>> '百分之计数:{num:%}'.format(num=100)
'百分之计数:10000.000000%'
>>> '{num:12}'
'{num:12}'
>>> '{num:12}'.format(num=22)
'          22'
>>> len('{num:12}'.format(num=22))
12
>>> '{num:10}gates'.format(num='bill')
'bill      gates'
>>> len('{num:10}gates'.format(num='bill'))
15
>>> 'float number:{pi:.2f}'.format(pi=pi)
'float number:3.14'
>>> 'float number:{pi:10.2f}'.format(pi=pi)
'float number:      3.14'
>>> '{:5}'.format('111111')
'111111'
>>> '千位分隔符:{:,}'.format(100**10)
'千位分隔符:100,000,000,000,000,000,000'
>>> '第{chapter:02.0f}章'.format(chapter=9)
'第09章'
>>> '{:<10.2f}\n{:^10.2f}\n{:>10.2f}'.format(1,2,3)
'1.00      \n   2.00   \n      3.00'
>>> '{:#^20}'.format('井号')
'#########井号#########'
>>> '{:b}'.format(100)
'1100100'
>>> '{0:^=10.2}'.format(-53.3)
'-^^5.3e+01'
>>> '{0:^=10.2}'.format(-5.33)
'-^^^^^^5.3'

number=int(input('请输入一个整数:'))
print('第{:0{number}.0f}章,第{:03.0f}节'.format(1,2,number=number))
>>> '<'+'hello'.center(30)+'>'
'<            hello             >'
>>> len('<'+'hello'.center(30)+'>')
32
>>> '<{:^30}>'.format('hello')
'<            hello             >'
>>> len('<'+'hello'.center(30,'*')+'>')
32
>>> '<'+'hello'.center(30,'*')+'>'
'<************hello*************>'
>>> '<{:*^30}>'.format('hello')
'<************hello*************>'
>>> s='hello world'
>>> s.find('hello')
0
>>> s.find('world')
6
>>> s.find('find')
-1
>>> s.find('o')
4
>>> s.find('o',5)
7
>>> s.find('l',3,4)
3

s=input('请输入一个英文短句:')
while True:
    zc=input('请输入要查询的英文单词:')
    if zc=='end':
        break
    syks=input('输入查询开始的位置:')
    syjs=input('输入查询结束的位置:')
    star=0
    end=len(s)
    if syks !='':
        star=int(syks)
    if syjs !='':
        end=int(syjs)
    print("'{}' 在'{}'出现的位置是{}: ".format(zc, s,s.find(zc,star,end)))

>>> list=['1','2','3','4','5']
>>> s.join(list)
'1&2&3&4&5'
>>> b.join(list1)
'a+b+c+d+e'
>>> dirs='','usr','local','nginx',''
>>> s='/'.join(dirs)
>>> print(s)
/usr/local/nginx/
>>> c='c:'+'\\'.join(dirs)
>>> print(c)
c:\usr\local\ngin
>>> '1.2.3.4.5'.split('.')
['1', '2', '3', '4', '5']
>>> list='/usr/local/nginx/'.split('/')
>>> list
['', 'usr', 'local', 'nginx', '']
>>> 'i like python'.split()
['i', 'like', 'python']


list=['Python','Ruby','Java','KOTLIN']
if 'KOTLIN' in list:
    print('找到了')
else:
    print('没找到!')

>>> s='abc abc abc abc anc abc abc abc abc abc'
>>> string.capwords(s)
'Abc Abc Abc Abc Anc Abc Abc Abc Abc Abc'
>>> s='abby JOHN jack'
>>> string.capwords(s)
'Abby John Jack'
>>> 'this is a bike'.replace('car','bike')
'this is a bike'
>>> 'this is a bike'.replace('bike','car')
'this is a car'
>>> x=['i','like','you']
>>> y='   you   '
>>> y in x
False
>>> y.strip() in x
True
>>> '***    &* hello &  *world** &&&'.strip(' *&')
'hello &  *world'
>>> s='i noot only like python,but also like kotlin.'
>>> table=s.maketrans('ak','*$')
>>> table
{97: 42, 107: 36}
>>> len(table)
2
>>> s.translate(table)
'i noot only li$e python,but *lso li$e $otlin.'
>>> s.maketrans('ak','$%',' ')
{97: 36, 107: 37, 32: None}
>>> s.translate(table)
'i noot only li$e python,but *lso li$e $otlin.'
>>> table1=s.maketrans('ak','$%',' ')
>>> s.translate(table1)
'inootonlyli%epython,but$lsoli%e%otlin.'

s=input('请输入一个英文字符串:')
x=0
while True:
    y=input('请输入要统计的字符串:')
    list(s)
    if y == 'end':
        break
    else:
        x=s.count(y)
        print('{}在{}中出现了{}次'.format(y,s,x))
print('程序结束!')
>>> names=['bill','mike','john','mary']
>>> numbers=['1234','4658','5554','5454']
>>> numbers[names.index('mike')]
'4658'
>>> names[numbers.index('5454')]
'mary'

#字典
'创建'
>>> pothonbook={"bill":"1234","mike":"1234","join":"1234","mary":"1234"}
>>> pothonbook
{'bill': '1234', 'mike': '1234', 'join': '1234', 'mary': '1234'}
>>> pothonbook={"bill":"1234",'bill':'4564',"mike":"4561","join":"6445","mary":"8894"}
>>> pothonbook['bill']
'4564'
>>> items=[['bill','2345'],['mike','4561'],['join','5465'],['mary','4564']]
>>> d=dict(items)
>>> d
{'bill': '2345', 'mike': '4561', 'join': '5465', 'mary': '4564'}
>>> d=dict(name='bill',number='1234',age=23)
>>> d
{'name': 'bill', 'number': '1234', 'age': 23}
>>> c=dict()
>>> c
{}

i=[]
while True:
    key=input('请输入key:')
    if key == 'end':
        break
    valuse=input('请输入values:')
    x=[key,valuse]
    i.append(x)
d=dict(i)
print(d)
请输入key:name
请输入values:key
请输入key:age
请输入values:50
请输入key:phton
请输入values:12346789
请输入key:end
{'name': 'key', 'age': '50', 'phton': '12346789'}

>>> d=dict(name='bill',number='1234',age=23)
>>> len(d)
3
>>> c['mike']={'age':30,'slary':3000}
>>> c
{'mike': {'age': 30, 'slary': 3000}}
>>> c['mike']
{'age': 30, 'slary': 3000}
>>> c['age']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
>>> c[(12,'mike',True)]='hello'
>>> c
{'mike': {'age': 30, 'slary': 3000}, (12, 'mike', True): 'hello'}
>>> c[12]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 12
>>> c[12,'mike',True]
'hello'
>>> list={}
>>> list[30]='age'
>>> list[30]='hellow'
>>> list
{30: 'hellow'}
>>> list[30]='age'
>>> list
{30: 'age'}
>>> list[30]='hellow'
>>> 30 in list
True


IDEs={
    'eclipse':
    {
        'languages':['java','python','php','JavaScript'],
        'organization':'Eclipse 基金会'
    },
    'vlsualstudio':
    {
    
        'languages':['c#','C++','VB.NET'],
        'organization':'微软'
    },
    'webstrom':
    {
        'languages':['JavaScript'],
        'organization':'JetBrains'     
    }
}
lambda1={
    'languages':'支持的编程语言',
    'organization':'所属机构'
}
IEDz=input('请输入IDE的名字:')
findide=IEDz.replace(' ', '').lower()
choice=input('要查询TDE支持的编程语言(lang)还是编程语言所属的机构(org)?')
if choice=='lang':key='languages'
if choice=='org':key='organization'

if findide in IDEs:
    print('{}{}是{}.'.format(IEDz,lambda1[key], IDEs[findide][key]))
#字典的格式化
>>> 'x,y, %d  abc %s'  % (20,'ok')
'x,y, 20  abc ok'
>>> valuese=(1,2,'hello')
>>> str='abc is %d,xy is %d ,%s world'
>>> str % valuese
'abc is 1,xy is 2 ,hello world'
values={'title':'花花大世界','url':'http://localhost:8888','company':'穆尼里奥'}
str1='''
<html>
    <head>
        <title>{title}</title>
        <mate charset='utf-8'>
    <head>
    <body>
    <h1>{title}</h1>
    <a href='{url}'>{company}</a>
    </body>
</html>
'''
print(str1.format_map(values))
'''
#序列与迭代
a={'x':1,'y':2,'z':3}
for key in a:#获取key值
    print(key,end=' ')

a={'x':1,'y':2,'z':3}
for key,values in a.items():#获取key和value
    print(key,values,end=' ')

#并行迭代
name=['song','zu','ying']
age=[20,30,40]
for i in range(len(name)):
    print(name[i],age[i],end=' ')

#压缩序列
a=[1,2,3,4]
b=['a','b','c','d','e']
for i in zip(a,b):
    print(i,end = ' ')
x 1 y 2 z 3
#翻转

a=reversed(['abc','呵呵','12345'])
for i in a:
    print(i,end = ' ')
12345 呵呵 abc
a={'name':'bill','age':34,'sex':'男','salary':'5000'}
for i in a :
    print(i, a[i],end=' ') 
print()
for x,y in a.items():
    print(x,y,end=' ')
print()

list1=[1,2,3,4,5]
list2=['a','b','c','d','e','f','g']
for i in range(len(list1)):
    print(list1[i],list2[i],end=' ')

for x in zip(list1,list2):
    print(x,end = ' ')

a=[4,2,3,4,5,6,7,8,9]#[2, 3, 4, 4, 5, 6, 7, 8, 9]
print(sorted(a))
s=reversed(a)
for i in s:
    print(i , end =' ')#9 8 7 6 5 4 3 2 4
#字典方法
>>> a={'x':1,'y':2,'z':3}
>>> a
{'x': 1, 'y': 2, 'z': 3}
>>> a.clear()#clear清空字典
>>> a
{}
#clear同时清除指向同一字典的值
>>> a={'x':1,'y':2,'z':3}
>>> b=a
>>> b
{'x': 1, 'y': 2, 'z': 3}
>>> a={}
>>> a
{}
>>> b
{'x': 1, 'y': 2, 'z': 3}#b不变

>>> a={'x':1,'y':2,'z':3}
>>> a=b
>>> a.clear()
>>> a
{}
>>> b
{}#a和b同时成为了空字典
#copy复制一个字典,浅复制
>>> a={'x':1,'y':2,'z':3}
>>> b=a.copy()
>>> b
{'x': 1, 'y': 2, 'z': 3}
#浅层复制
>>> list={'name':'bill','age':30,'fullname':['bill','gates']}
>>> list1=list.copy()
>>> print('list',list)
list {'name': 'bill', 'age': 30, 'fullname': ['bill', 'gates']}
>>> print('list1',list)
list1 {'name': 'bill', 'age': 30, 'fullname': ['bill', 'gates']}
#第一层修改只改变当前字典
>>> list1['age']= 54
>>> list1
{'name': 'bill', 'age': 54, 'fullname': ['bill', 'gates']}
>>> list
{'name': 'bill', 'age': 30, 'fullname': ['bill', 'gates']}
#第二层修改原有列表页会改变
>>> list1['fullname'][1]= 'clinton'
>>> list
{'name': 'bill', 'age': 30, 'fullname': ['bill', 'clinton']}
>>> list1
{'name': 'bill', 'age': 54, 'fullname': ['bill', 'clinton']}
#那么可不可以复制的字典不受影响呢?答案是可以的,用deepcopy进行深层复制,看例子
>>> list={'name':'bill','age':30,'fullname':['bill','gates']}
>>> list1=list.copy()#浅层复制
>>> li>>> list1['fullname'][1]= 'clinton'
>>> list
{'name': 'bill', 'age': 30, 'fullname': ['bill', 'clinton']}#原有字典改变
>>> list1
{'name': 'bill', 'age': 30, 'fullname': ['bill', 'clinton']}#浅层复制改变
>>> list2
{'name': 'bill', 'age': 30, 'fullname': ['bill', 'gates']}#深层复制未发生改变
#fromkeys方法 根据key建立字典,value 默认值为none
>>> list={}.fromkeys(['name','age','salary'])
>>> list
{'name': None, 'age': None, 'salary': None}
>>> list1=list.fromkeys(('name','age','salary'))
>>> list1
{'name': None, 'age': None, 'salary': None}
>>> list2=list.fromkeys(['name','age','salary'],'666')#设置默认值
{'name': '666', 'age': '666', 'salary': '666'}
#get方法,不会抛出异常
>>> a=list2['names']#dict[key]查询不存在会抛出异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'names'

>>> list2.get('names',666)#get不存会时默认返回none,也可指定返回值
666

#用get方法获取key对应的值
dict={'help':'帮助','hello':'你好','name':'名字','china':'中国'}
while True:
    i=input('输入要查询的单词:')
    if i=='exit':
        break
    x=dict.get(i)
    if x == None:
        print('查找的单词不存在')
    else:
        print('{}的中文意思是{}'.format(i,x))
print('程序结束!')
#items 和keys方法 直接看例子

dict={'help':'帮助','hello':'你好','name':'名字','china':'中国'}
print(dict.items())
for key_value in dict.items():#迭代key值
    print('key','=',key_value[0],'value','=',key_value[1])
print(('china','中国') in dict.items())#查询是否存在dict.items的返回值中
dict_items=dict.items()
dict['hello']='你好,我好,大家好!'#修改字典中的值
print(dict_items)#对所有的key 进行迭代
for key in dict.keys():
    print(key)

#pop 方法和popitem方法
>>> a={'a':1,'b':2,'c':3,'d':4}
>>> a['e']=5
>>> a
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> a.pop('b')
2

a={'a':1,'b':2,'c':3,'d':4}#
a['e']=5
for i in range(len(a)):
    print(a.popitem())
('e', 5)
('d', 4)
('c', 3)
('b', 2)
('a', 1)
#setdefault方法
>>> dict={}
>>> print(dict.setdefault('name','bill'))
bill
>>> dict
{'name': 'bill'}
>>> dict.setdefault('name','mike')
'bill'
>>> dict
{'name': 'bill'}
>>> dict.setdefault('age')
>>> dict
{'name': 'bill', 'age': None}
#update 方法
>>> list={'name': 'bill', 'age': None}
>>> list1={'name': 'mike', 'age': 100,'salary':'5000'}
>>> list.update(list1)
>>> list.update(list1)
>>> list,list1
({'name': 'mike', 'age': 100, 'salary': '5000'}, \
{'name': 'mike', 'age': 100, 'salary': '5000'})
#values 方法

dict={'a':1,'b':2,'c':3,'d':4}
print(dict.values)
for i in dict.values():
    print(i)
'''
#类和对象
class Person:
    def setName(self,name):
        self.name=name
    def getName(self):
        return self.name
    def greet(self):
        print('hello,im {name}.'.format(name=self.name))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值