基礎數據類型(不可變數據類型)


可變數據類型和不可變數據類型的定義

不可變數據類型:

    即不可以在源數據的基礎上發生改變,如果想要通過某些運算或者方法來改變源數據,則會重新開辟空間存儲結果,並不會影響源數據

1 a = 3
2 print(id(a + 3))
3 print(id(a))
4 
5 
6 """
7 1623616688
8 1623616592
9 """
示例

 

可變數據類型 :

    即可以在源數據的基礎上發生改變,內存地址不會發生改變

1 a = [1,2,3]
2 print(id(a))
3 a += [2,3,4]
4 print(id(a))
5 
6 """
7 2243534804936
8 2243534804936
9 """
示例
 1 a = [1,2,3]
 2 print(id(a))
 3 a = a + [2,3,4]
 4 print(id(a))
 5 
 6 """
 7 2875843041224
 8 2875843041096
 9 列表在做+運算的時候,不管是可變數據類型還是不可變數據類型都會重新開辟空間存放結果,
10 """
11 
12 a = [1,2,3]
13 print(id(a))
14 a += [2,3,4]
15 print(id(a))
16 
17 """
18 1827113031624
19 1827113031624
20 +=運算會判斷其數據類型是否可變,如果可變則在原基礎上運算,如果不可變則會重新開辟空間
21 """
特殊情況

 

1. 整型 (int)

    數字,用以計算比較

#python2 中沒有int類型
    long(長整型) / 獲取的是整數 -->int類型
#python3 中 整型int --> 整數

32位/64位 范圍

  1. 整型的32位  -2 ** 31  ~  2 **31-1
  2. 整型的64位  -2** 63 ~  2 **63-1

十二進制轉成二進制的計算方法

56取余2 (余為0) 的商取余2 (余為0) 反復計算 直至商為1 得出的結果為余的倒序排列(0b為utf-8的固定格式)0b110001

56  0
28  0
14  0
7   1
3   1
1   1  
print(bin(56))

二進制轉成十進制的計算方法

111000  # 從右向左進行計算(先做冪運算)
0 * 2 ** 0 + 0 * 2 ** 1 + 0 * 2 ** 2 + 1 * 2**3 + 1*2 ** 4 +1 * 2** 5
0 + 0 + 0 + 8 + 16 + 32 =56
print(int("10101",2))  

2. 字符串(str)

在python中只要是用引號引起來的就是字符串(str)

加法 -- 同是字符串才能相加

乘法 -- 只能和數字進行相乘

a = "my name's xiaoxiao"

1. 字符串拼接

   a = '5'

   b = '8'

print(a+b)   # '58' 只能和字符串相加

2. 字符串相乘

a = '堅強'*8
print(a) # '堅強堅強堅強堅強堅強堅強堅強堅強'

注釋 編碼錯誤

解決方法:

 -*-coding:utf-8 -*-   #python 2 

3. 字符串轉義

a = '58'
b = '你好'          
c = 'abc'          
a1 = int(a)       # int 要轉換的內容只有帶着引號的數字才可以  
print(type(a1))    # <class 'int'>

str()              # str 要轉換的內容沒有限制

4. 字符串的索引,切片,步長

    字符串,就是由字符組成的串。字符又包括數字、字母、符號等

在python中引號引起來就是字符串
# 字符串是用來存儲少量數據(512MB),

#索引(下標)
# name = "meat"
# meat 每一個字母叫做一個元素      

5. 索引(下標)msg = '天王蓋地虎,小雞燉蘑菇.' 

a = '你好你好'                  #字符串:存儲一些數據
#   0 1 2 3       #從左往右: 0-n #下標
#   -4 -3 -2 -1               # 從右往左:-1:(-n)   字符串的長度

print(msg[7])                  #'雞'
print(msg[-5])                 #'雞'
1 class str():
2   def __getitem__(self, *args, **kwargs): # real signature unknown
3       """ Return self[key]. """
4       pass
[]的源碼
 
        

6. 切片

#切片 
print(msg[7:9])                #把小雞打印出來 特性:顧頭不顧尾,7為小 起始位置,9為尾 結尾位置.
print(msg[9:7:-1])             #1表示從左往右,-1表示方向從右往左

7. 切片加步長

print(msg[7:9:2])              #小燉   默認不寫為1步長.切片的時候起始位置和終止位置都超出的時候不會進行報錯
print(msg[1])                  #索引查找如果過界就報錯,切片的時候就獲取到最后一個內容
print(msg[-6:-4])              #把小雞打印出來   #-6為起始位置 -4為終止位置  

3. 字符串方法

1.capitalize(首字母大寫)

1 s = 'alex'      
2 # 首字母大寫
3 s2 = s.capitalize()   
4 print(s2)      
5 
6 """
7 'Alex'
8 ''"
示例
1 ef capitalize(self): # real signature unknown; restored from __doc__
2         """
3         S.capitalize() -> str
4         
5         Return a capitalized version of S, i.e. make the first character
6         have upper case and the rest lower case.
7         """
8         return ""
源碼

2. title(每個單詞首字母大寫)

1 s = 'alex'    
2 # 首字母大寫
3 s2 = s.capitalize()   
4 print(s2)
5 
6 """
7 'Alex'
8 """
示例
1     def title(self): # real signature unknown; restored from __doc__
2         """
3         S.title() -> str
4         
5         Return a titlecased version of S, i.e. words start with title case
6         characters, all remaining cased characters have lower case.
7         """
8         return ""
源碼

3. upper(全部大寫)

1 #  全部大寫
2 s = 'abc'
3 s3 = s.upper()    
4 print(s2)
5 
6 
7 """
8 'ABC'
9 """
示例
1  def upper(self): # real signature unknown; restored from __doc__
2         """
3         S.upper() -> str
4         
5         Return a copy of S converted to uppercase.
6         """
7         return ""
源碼

4. lower(全部小寫)

1 #全部小寫
2 a = 'ABC'
3 s4 = s.lower()     
4 print(s4)
5 
6 """
7 'abc'
8 """
示例
1 #字符串大小寫做驗證碼
2 my_yzm = 'Z98k'
3 yzm = input("請輸入驗證碼:(Z98k)")
4 if yzm.upper() == my_yzm.upper():
5     print("驗證碼正確.")
6 else:
7     print("請重新輸入.")
1 def lower(self): # real signature unknown; restored from __doc__
2     """
3     S.lower() -> str
4         
5     Return a copy of the string S converted to lowercase.
6     """
7     return ""
源碼

5. count(計數)

1 #返回的是數量,計數,字符串里有幾個L
2 s == 'alEkLx'
3 print(s.count('L'))   
4 
5 """
6 1
7 """
示例
1     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
2         """
3         S.count(sub[, start[, end]]) -> int
4         
5         Return the number of non-overlapping occurrences of substring sub in
6         string S[start:end].  Optional arguments start and end are
7         interpreted as in slice notation.
8         """
9         return 0
源碼

6. startwith/endwith(以什么開頭/結尾)

 1 #判斷是不是以x結尾
 2 print(s.endswith('x')) 
 3 """
 4 True
 5 """ 6 
 7  #判斷是不是以a開頭
 8 print(s.startswith('a')) 
 9 
10 """
11 False
12 """
示例
 1     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
 2         """
 3         S.endswith(suffix[, start[, end]]) -> bool
 4         
 5         Return True if S ends with the specified suffix, False otherwise.
 6         With optional start, test S beginning at that position.
 7         With optional end, stop comparing S at that position.
 8         suffix can also be a tuple of strings to try.
 9         """
10         return False
endwith源碼
 1     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
 2         """
 3         S.startswith(prefix[, start[, end]]) -> bool
 4         
 5         Return True if S starts with the specified prefix, False otherwise.
 6         With optional start, test S beginning at that position.
 7         With optional end, stop comparing S at that position.
 8         prefix can also be a tuple of strings to try.
 9         """
10         return False
startwith源碼

7. find()/index(通過元素找下標)

1 #通過元素查找下標,查找沒有的返回-1,從左向右只查一個
2 print(s.find('L'))  
3 
4 print(s.index('L'))     #沒有的話報錯      ValueError: substring not found
示例
 1     def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 2         """
 3         S.find(sub[, start[, end]]) -> int
 4         
 5         Return the lowest index in S where substring sub is found,
 6         such that sub is contained within S[start:end].  Optional
 7         arguments start and end are interpreted as in slice notation.
 8         
 9         Return -1 on failure.
10         """
11         return 0
源碼
 1     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 2         """
 3         S.index(sub[, start[, end]]) -> int
 4         
 5         Return the lowest index in S where substring sub is found, 
 6         such that sub is contained within S[start:end].  Optional
 7         arguments start and end are interpreted as in slice notation.
 8         
 9         Raises ValueError when the substring is not found.
10         """
11         return 0
源碼

8.format(格式化)

1 s == 'alEkLx'
2 print(s.format())    #alEkLx    
3 4 s == 'alEkLx{},{},{}'   #按照位置進行填充
5 print(s.format('你好','','少年'))            # alEkLx你好,啊,少年
6 s == 'alEkLx{0},{2},{1}'    #按照索引進行填充
7 print(s.format('你好','','少年'))            # alEkLx你好,少年,啊
8 s == 'alEkLx{a},{b},{c}'    #按照關鍵字指定內容進行填充
9 print(s.format(a='你好',b='',c='少年'))      #alEkLx你好,啊,少年
示例
1     def format(self, *args, **kwargs): # known special case of str.format
2         """
3         S.format(*args, **kwargs) -> str
4         
5         Return a formatted version of S, using substitutions from args and kwargs.
6         The substitutions are identified by braces ('{' and '}').
7         """
8         pass
源碼

9. join(拼接)

1 #插入字符串里面的內容  (可迭代對象)
2 s == 'alEkLx'
3 print(s.join('_'))                   # 不能這么用  
4 print('_'.join(s))                   # a_l_E_k_L_x   
5                                     #拼接的符號.join(可迭代的對象)
示例
1     def join(self, iterable): # real signature unknown; restored from __doc__
2         """
3         S.join(iterable) -> str
4         
5         Return a string which is the concatenation of the strings in the
6         iterable.  The separator between elements is S.
7         """
8         return ""
源碼

10. split(分割)

1 #*** 分割    返回的是列表  以空格/換行符(\n)/制表符(\t)進行分割
2 s == 'alEkLx{a},{b},{c}' 
3 print(s.split('x'))                  #['alEkL','{a},{b},{c}']
4 print(s.split('x',maxspilt=1))        #指定數量 
示例
 1     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
 2         """
 3         S.split(sep=None, maxsplit=-1) -> list of strings
 4         
 5         Return a list of the words in S, using sep as the
 6         delimiter string.  If maxsplit is given, at most maxsplit
 7         splits are done. If sep is not specified or is None, any
 8         whitespace string is a separator and empty strings are
 9         removed from the result.
10         """
11         return []
源碼

11. strip(脫)

1 #***脫_脫掉頭尾兩邊的空格/換行符(\n)/制表符(\t)
2 s == '   alEkLx{a},{b},{c}   '
3 print(s.strip(s))                     #alEkLx{a},{b},{c}  
4 print(s.strip(' '))                   # alEkLx{a},{b},{c}
5 print(s.strip('  a'))                 # lEkLx{a},{b},{c}
6 s == '   alEkLx{a},{b},{c}a   '
7 print(s.strip('  a'))                 # lEkLx{a},{b},{c}
示例
1     def strip(self, chars=None): # real signature unknown; restored from __doc__
2         """
3         S.strip([chars]) -> str
4         
5         Return a copy of the string S with leading and trailing
6         whitespace removed.
7         If chars is given and not None, remove characters in chars instead.
8         """
9         return ""
源碼

12. replace(替換)

1 #替換 第一個放要被替換的,第二個放替換的內容
2 s = 'alEkLx{a},{b},{c}a'
3 print(s.replace('a','s',1))                     #'slEkLx{a},{b},{c}s'
示例
1     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
2         """
3         S.replace(old, new[, count]) -> str
4         
5         Return a copy of S with all occurrences of substring
6         old replaced by new.  If the optional argument count is
7         given, only the first count occurrences are replaced.
8         """
9         return ""
源碼

13. 大小寫轉換

 #大小寫轉換
print(s.swapcase(s))                #ALeKLX{A},{B},{C}A

14. 居中

name = 'alex'
print(name.center(20,'*'))      #***********alex**********

15. is系列

is系列
#判斷字符串里面的內容是不是全是阿拉伯數字,但是②不行
print(s,isdigit())

#判斷字符串里面是不是漢字和字母
print(s.isalpha())

#判斷字符串是不是字母,數字,中文
print(s.isalnum())

#判斷字符串是不是十進制
print(s.isdecimal())

16. 編碼

#編碼   編碼集
s1 = s.encode('utf-8')
print(s1)

a = 'alex'
a1 = a.encode('utf-8')    
print(a1)         #b'alex'
a2 = a.encode('gbk')
pring(a2)         #b'alex'

17. 解碼

#解碼
a3 = s.encode('utf-8')
print(a3.decode('gbk'))     # 不能使得

s = 'alex'
s1 = s.encode('utf-8')   # 編碼     utf-8 包含了ascii
print(s1.decode('gbk')) # 解碼     gbk   包含了ascii
                        # 應用場景: 文件操作   網絡傳輸   網絡編程

18. 開辟新的空間

name = "alex"
name1 = "wusir"
print(id(name))
print(id(name1))
print(id(name + name1))

4. 布爾值(bool):

Turs#(真的)   False#(假的)

s(變量名) =(賦值) 5(值)

#數字轉成布爾值 非0 的都是True
print(bool(55))              #True
print(bool("你好"))           #True   不是空的就是True
print(bool(""))              #False

#布爾值轉換成數字
print(int(True))             #1
print(int(False))            #0

#布爾值轉換成字符串
msg = str(True)
print(msg)
print(type(msg))             #True   但是是str的數據類型

#布爾值
print(bool(1))  # 數字非零的就是True 零就是False
print(bool("")) # 字符串不為空就是True ,字符串中沒有任何內容就是False
取余2

5. 元組: (tuple )

不可變數據,不能被修改,用來存放一些用戶密碼**  在配置文件中使用
#元組就是一個不可以修改的列表
tu = (1,2,3,4,'你好啊'')
print(tu[2:5])           #元組切片切出來的是元組
print(tu[2:5:2])         #切片+步長

#元組修改方法   改成列表形式再進行修改
tu = list(tu)
print(tu)

tu = ("你好")
tu = ("你好",)         #有逗號的是元組
tu = ()                #空的是元組
     
tu = ('12')
print(type(tu))        #數據類型是()中的數據本身
     
#可以加 可以乘數字
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM