Python學習【第2篇】:Python之資料類型

來源:互聯網
上載者:User

標籤:tin   inf   先進後出   input   pytho   html   空白   while   dfa   

數字類型和字串類型

1.bin()函數將十進位轉換成而進位

2.oct()函數將十進位轉換成八進位

3.hex()函數將十進位轉換成十六進位     

    十六進位表示:0-9 a b c d e f

4.數字類型的特性:    

    只能存放一個值  

    一經定義,不可更改

     直接存取

分類:整型,布爾,浮點,複數

5.字串類型  

  引號包含的都是字串類型

    S1=‘hello world‘  s="hello world"

    s2="""hello world"""  

    s3=‘‘‘hello world‘‘‘  

  單引雙引沒有區別

6.字串的常用操作  

  strip()移除空白,也可以去除其他的字元  

  slipt()分割,預設以空格分割。也可以以其他的字元分割  

  len()長度  切片:如print(x[1:3])也是顧頭不顧尾   

            print(x[0:5:2])#0 2 4

  capitalize()首字母大寫

   center()置中顯樣本如:x=‘hello‘  print(x.center(30,‘#‘))

   count():計數,顧頭不顧尾,統計某個字元的個數,空格也算一個字元  

  endswith()以什麼結尾

   satrtswith()以什麼開頭

   find()尋找字元的索引位置,如果是負數,代表尋找失敗   

  index()索引  

  find()和index()的區別,如:

      

  format()字串格式化    

     1.msg=‘name:{},age:{},sex:{}‘           

        print(msg.format(‘haiyan‘,18,女))  

      2.msg=‘name:{0},age:{1},sex:{0}‘     

     print(msg.format(‘aaaaaa‘,‘bbbbbb‘))    

    3.msg=‘name:{x},age:{y,sex:{z}‘     

     print(msg.format(x=‘haiyan‘,y=‘18‘,z=‘女‘))  

  isdigit()判斷是否是數字

   islower()判斷是否是全部小寫

   isupper()判斷是否是全部大寫

   lower()全部轉換為小寫

   upper()全部轉換為大寫

   isspace()判斷是否是全都是空格

   istitle()判斷是否是標題(首字母大寫)  

  swapcase()大小寫字母翻轉

   join()串連

   repalce()替換   

     msg=‘hello alex‘   

     print(msg.replace(‘e‘),‘A‘,1)  

     print(msg.replace(‘e‘),‘A‘,2)

   ljust()靠左對齊   

     X=‘ABC‘    print(x.ljust(10,‘*‘))

 

 

 

字串格式化及字串的一些方法

1.%s,%d

舉例1:name=‘egon‘

     age=20

     print("my name is %s  my age is %s" %(name,age))#%s既能接受字串,也能接受數字

     print(‘my name is %s  my age is %d’ %(name,age))#%d只能接受數字

舉例2:使用者資訊的顯示

 1 while True: 2     name=input("name:") 3     age=input("age:") 4     sex=input("sex:") 5     height=input("height:") 6     msg=‘‘‘ 7              ------------%s info----------- 8              name:%s 9              age:%s10              sex:%s11              height:%s12              ------------------------------13         ‘‘‘%(name,name,age,sex,heigth)14     print(msg)

運行結果如下:

 

 2.字串方法

 

# name=‘egon‘ #name=str(‘egon‘)# print(type(name))#優先掌握#1.移除空白strip# msg=‘             hello         ‘# print(msg)# print(msg.strip())# 移除‘*’# msg=‘***hello*********‘# msg=msg.strip(‘*‘)# print(msg)#移除左邊的# print(msg.lstrip(‘*‘))#移除右邊的# print(msg.rstrip(‘*‘))#用處while True:    name=input(‘user: ‘).strip()    password=input(‘password: ‘).strip()    if name == ‘egon‘ and password == ‘123‘:        print(‘login successfull‘)#切分split# info=‘root:x:0:0::/root:/bin/bash‘# print(info[0]+info[1]+info[2]+info[3])# user_l=info.split(‘:‘)# print(user_l[0])# msg=‘hello world egon say hahah‘# print(msg.split()) #預設以空格作為分隔字元#cmd=‘download|xhp.mov|3000‘# cmd_l=cmd.split(‘|‘)# print(cmd_l[1])# print(cmd_l[0])# print(cmd.split(‘|‘,1))#用處while True:    cmd=input(‘>>: ‘).strip()    if len(cmd) == 0:continue    cmd_l=cmd.split()    print(‘命令是:%s 命令的參數是:%s‘ %(cmd_l[0],cmd_l[1]))#長度len# print(len(‘hell 123‘))#索引# 切片:切出子字串# msg=‘hello world‘# print(msg[1:3]) #1 2# print(msg[1:4]) #1 2 3# 掌握部分oldboy_age=84while True:    age=input(‘>>: ‘).strip()    if len(age) == 0:        continue    if age.isdigit():        age=int(age)    else:        print(‘must be int‘)#startswith,endswith# name=‘alex_SB‘# print(name.endswith(‘SB‘))# print(name.startswith(‘alex‘))#replace# name=‘alex say :i have one tesla,my name is alex‘# print(name.replace(‘alex‘,‘SB‘,1))# print(‘my name is %s my age is %s my sex is %s‘ %(‘egon‘,18,‘male‘))# print(‘my name is {} my age is {} my sex is {}‘.format(‘egon‘,18,‘male‘))# print(‘my name is {0} my age is {1} my sex is {0}: {2}‘.format(‘egon‘,18,‘male‘))# print(‘my name is {name} my age is {age} my sex is {sex}‘.format(#     sex=‘male‘,#     age=18,#     name=‘egon‘))# name=‘goee say hello‘# # print(name.find(‘S‘,1,3)) #顧頭不顧尾,找不到則返回-1不會報錯,找到了則顯示索引# # print(name.index(‘S‘)) #同上,但是找不到會報錯## print(name.count(‘S‘,1,5)) #顧頭不顧尾,如果不指定範圍則尋找所有#join# info=‘root:x:0:0::/root:/bin/bash‘# print(info.split(‘:‘))# l=[‘root‘, ‘x‘, ‘0‘, ‘0‘, ‘‘, ‘/root‘, ‘/bin/bash‘]# print(‘:‘.join(l))#lower,upper# name=‘eGon‘# print(name.lower())# print(name.upper())#瞭解部分#expandtabs# name=‘egon\thello‘# print(name)# print(name.expandtabs(1))#center,ljust,rjust,zfill# name=‘egon‘# # print(name.center(30,‘-‘))# print(name.ljust(30,‘*‘))# print(name.rjust(30,‘*‘))# print(name.zfill(50)) #用0填充#captalize,swapcase,title# name=‘eGon‘# print(name.capitalize()) #首字母大寫,其餘部分小寫# print(name.swapcase()) #大小寫翻轉# msg=‘egon say hi‘# print(msg.title()) #每個單詞的首字母大寫#在python3中num0=‘4‘num1=b‘4‘ #bytesnum2=u‘4‘ #unicode,python3中無需加u就是unicodenum3=‘四‘ #中文數字num4=‘Ⅳ‘ #羅馬數字#isdigt:str,bytes,unicode# print(num0.isdigit())# print(num1.isdigit())# print(num2.isdigit())# print(num3.isdigit())# print(num4.isdigit())#isdecimal:str,unicode# num0=‘4‘# num1=b‘4‘ #bytes# num2=u‘4‘ #unicode,python3中無需加u就是unicode# num3=‘四‘ #中文數字# num4=‘Ⅳ‘ #羅馬數字# print(num0.isdecimal())# # print(num1.)# print(num2.isdecimal())# print(num3.isdecimal())# print(num4.isdecimal())#isnumeric:str,unicode,中文,羅馬# num0=‘4‘# num1=b‘4‘ #bytes# num2=u‘4‘ #unicode,python3中無需加u就是unicode# num3=‘四‘ #中文數字# num4=‘Ⅳ‘ #羅馬數字## print(num0.isnumeric())# # print(num1)# print(num2.isnumeric())# print(num3.isnumeric())# print(num4.isnumeric())#is其他# name=‘egon123‘# print(name.isalnum()) #字串由字母和數字組成# name=‘asdfasdfa sdf‘# print(name.isalpha()) #字串只由字母組成## name=‘asdfor123‘# print(name.isidentifier())name=‘egGon‘print(name.islower())# print(name.isupper())# print(name.isspace())name=‘Egon say‘print(name.istitle())

列表

一、列表

  作用:多個裝備,多個愛好,多門課程,多個女朋友等

  定義:[]內可以有多個任意類型的值,逗號分隔

以下是列表的常用操作:

 

  1 l=[1,2,3] #l=list([1,2,3])  2 # print(type(l))  3   4 #pat1===》優先掌握部分  5 #  索引:l=[1,2,3,4,5]  6       print(l[0])  7 #  切片  8 l=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘]  9  10 # print(l[1:5]) 11 # print(l[1:5:2]) 12 # print(l[2:5]) 13 # print(l[-1]) 14  15  16 #瞭解 17 # print(l[-1:-4]) 18 # print(l[-4:]) 19 # l=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘] 20 # print(l[-2:]) 21  22 #   追加 23 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘] 24 # hobbies.append(‘girls‘) 25 # print(hobbies) 26  27 #   刪除 28 hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘] 29 # x=hobbies.pop(1) #不是單純的刪除,是刪除並且把刪除的元素返回,我們可以用一個變數名去接收該傳回值 30 # print(x) 31 # print(hobbies) 32  33 # x=hobbies.pop(0) 34 # print(x) 35 # 36 # x=hobbies.pop(0) 37 # print(x) 38  39 #隊列:先進先出 40 queue_l=[] 41 #入隊 42 # queue_l.append(‘first‘) 43 # queue_l.append(‘second‘) 44 # queue_l.append(‘third‘) 45 # print(queue_l) 46 #出隊 47 # print(queue_l.pop(0)) 48 # print(queue_l.pop(0)) 49 # print(queue_l.pop(0)) 50  51  52 #堆棧:先進後出,後進先出 53 # l=[] 54 # #入棧 55 # l.append(‘first‘) 56 # l.append(‘second‘) 57 # l.append(‘third‘) 58 # #出棧 59 # print(l) 60 # print(l.pop()) 61 # print(l.pop()) 62 # print(l.pop()) 63  64 #瞭解 65 # del hobbies[1] #單純的刪除 66 # hobbies.remove(‘eat‘) #單純的刪除,並且是指定元素去刪除 67  68  69 #   長度 70 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘] 71 # print(len(hobbies)) 72  73 #   包含in 74 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘] 75 # print(‘sleep‘ in hobbies) 76  77 # msg=‘hello world egon‘ 78 # print(‘egon‘ in msg) 79  80  81 ##pat2===》掌握部分 82 hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘] 83 # hobbies.insert(1,‘walk‘) 84 # hobbies.insert(1,[‘walk1‘,‘walk2‘,‘walk3‘]) 85 # print(hobbies) 86  87 # print(hobbies.count(‘eat‘)) 88 # print(hobbies) 89 # hobbies.extend([‘walk1‘,‘walk2‘,‘walk3‘]) 90 # print(hobbies) 91  92 hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘] 93 # print(hobbies.index(‘eat‘)) 94  95  96 #pat3===》瞭解部分 97 hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘] 98 # hobbies.clear() 99 # print(hobbies)100 101 # l=hobbies.copy()102 # print(l)103 104 # l=[1,2,3,4,5]105 # l.reverse()106 # print(l)107 108 l=[100,9,-2,11,32]109 l.sort(reverse=True)110 print(l)

Python學習【第2篇】:Python之資料類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.