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))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章