Python(變量、數據類型)

 

常量:
python中沒有常量,只能經過名字特徵來提示
例如:
所有大寫,如 : OLDBOY_AGE=57html

 

一.變量

變量
聲明變量
#!/usr/bin/env python

age=18
gender1='male'
gender2='female'

變量做用:保存狀態(程序的運行本質是一系列狀態的變化,變量的目的就是用來保存狀態,變量值的變化就構成了程序運行的不一樣結果。)
例如:CS槍戰,一我的的生命能夠表示爲life=active表示存活,當知足某種條件後修改變量life=inactive表示死亡。
  • 變量命名規則遵循標識符命名規則,詳見第二篇
  • name='lhf':'lhf'纔是內存變量,name只是內存變量的引用
  • 與c的區別在於變量賦值操做無返回值
  • 鏈式賦值:y=x=a=1
  • 多元賦值:x,y=1,2 x,y=y,x
  • 增量賦值:x+=1

 

二.數據類型

2.1 什麼是數據類型及數據類型分類

程序的本質就是驅使計算機去處理各類狀態的變化,這些狀態分爲不少種

例如英雄聯盟遊戲,一我的物角色有名字,錢,等級,裝備等特性,你們第一時間會想到這麼表示
名字:德瑪西亞------------>字符串
錢:10000 ------------>數字
等級:15 ------------>數字
裝備:鞋子,日炎斗篷,蘭頓之兆---->列表
(記錄這些人物特性的是變量,這些特性的真實存在則是變量的值,存不一樣的特性須要用不一樣類型的值)

python中的數據類型
python使用對象模型來存儲數據,每個數據類型都有一個內置的類,每新建一個數據,實際就是在初始化生成一個對象,即全部數據都是對象
對象三個特性
  • 身份:內存地址,能夠用id()獲取
  • 類型:決定了該對象能夠保存什麼類型值,可執行何種操做,需遵循什麼規則,可用type()獲取
  • 值:對象保存的真實數據
注:咱們在定義數據類型,只需這樣:x=1,內部生成1這一內存對象會自動觸發,咱們無需關心


這裏的字符串、數字、列表等都是數據類型(用來描述某種狀態或者特性)除此以外還有不少其餘數據,處理不一樣的數據就須要定義不一樣的數據類型
標準類型  其餘類型
數字 類型type
字符串 Null
列表 文件
元組 集合
字典 函數/方法
 
  模塊










 

2.2 標準數據類型:

2.2.1 數字

定義:a=1python

特性:git

1.只能存放一個值api

2.一經定義,不可更改bash

3.直接訪問網絡

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

 

2.2.1.1 整型:

Python的整型至關於C中的long型,Python中的整數能夠用十進制,八進制,十六進制表示。less

>>> 10
10         --------->默認十進制
>>> oct(10)
'012'      --------->八進制表示整數時,數值前面要加上一個前綴「0」
>>> hex(10)
'0xa'      --------->十六進制表示整數時,數字前面要加上前綴0X或0x

python2.*與python3.*關於整型的區別python2.7

python2.*
在32位機器上,整數的位數爲32位,取值範圍爲-2**31~2**31-1,即-2147483648~2147483647

在64位系統上,整數的位數爲64位,取值範圍爲-2**63~2**63-1,即-9223372036854775808~9223372036854775807
python3.*整形長度無限制

2.2.1.2 長整型long:

python2.*:
跟C語言不一樣,Python的長整型沒有指定位寬,也就是說Python沒有限制長整型數值的大小,
可是實際上因爲機器內存有限,因此咱們使用的長整型數值不可能無限大。
在使用過程當中,咱們如何區分長整型和整型數值呢?
一般的作法是在數字尾部加上一個大寫字母L或小寫字母l以表示該整數是長整型的,例如:
a = 9223372036854775808L
注意,自從Python2起,若是發生溢出,Python會自動將整型數據轉換爲長整型,
因此現在在長整型數據後面不加字母L也不會致使嚴重後果了。

python3.*
長整型,整型統一歸爲整型
python2.7
>>> a=9223372036854775807
>>> a
>>> a+=1
>>> a
9223372036854775808L

python3.5
>>> a=9223372036854775807
>>> a
>>> a+=1
>>> a

查看

 

'''
# print(type(n))
# print(type(f))

# print(1.3e-3)
# print(1.3e3)



# print(bin(10))     #二進制
# print(oct(10))     #八進制
# # 0-9 a b c d e f
# print(hex(10))     #16進制
'''


#數字類型的特色:
# 1.只能存放一個值
#
# 2.一經定義,不可更改,更改的是變量和值的對應關係
#
# 3.直接訪問
# x=10123123123
# print(id(x))
# x=11
# print(id(x))
# print(id(11))
#====================運行結果:=====================
# D:\Python36\python.exe D:/py/train.py
# 2368243792624
# 1640347008
# 1640347008
# Process finished with exit code 0
#================================================

2.2.1.3 布爾bool:

True 和False
1和0

2.2.1.4 浮點數float:

Python的浮點數就是數學中的小數,相似C語言中的double。
在運算中,整數與浮點數運算的結果是浮點數
浮點數也就是小數,之因此稱爲浮點數,是由於按照科學記數法表示時,
一個浮點數的小數點位置是可變的,好比,1.23*109和12.3*108是相等的。
浮點數能夠用數學寫法,如1.23,3.14,-9.01,等等。可是對於很大或很小的浮點數,
就必須用科學計數法表示,把10用e替代,1.23*109就是1.23e9,或者12.3e8,0.000012
能夠寫成1.2e-5,等等。
整數和浮點數在計算機內部存儲的方式是不一樣的,整數運算永遠是精確的而浮點數運算則可能會有
四捨五入的偏差。

2.2.1.5 複數complex:

複數由實數部分和虛數部分組成,通常形式爲x+yj,其中的x是複數的實數部分,y是複數的虛數部分,這裏的x和y都是實數。
注意,虛數部分的字母j大小寫均可以,
>>> 1.3 + 2.5j == 1.3 + 2.5J
True
 

2.2.1.6 數字相關內建函數

 

 

2.2.2 字符串

定義:它是一個有序的字符的集合,用於存儲和表示基本的文本信息,‘’或「」或‘’‘ ’‘’中間包含的內容稱之爲字符串
特性:
1.只能存放一個值
2.不可變
3.按照從左到右的順序定義字符集合,下標從0開始順序訪問,有序
補充:
  1.字符串的單引號和雙引號都沒法取消特殊字符的含義,若是想讓引號內全部字符均取消特殊意義,在引號前面加r,如name=r'l\thf'
  2.unicode字符串與r連用必需在r前面,如name=ur'l\thf'

2.2.2.1 字符串建立

‘hello world’ide

2.2.2.2 字符串經常使用操做

移除空白
分割
長度
索引
切片

2.2.2.3 字符工廠函數str()

 

  1 class str(object):
  2     """
  3     str(object='') -> str
  4     str(bytes_or_buffer[, encoding[, errors]]) -> str
  5 
  6     Create a new string object from the given object. If encoding or
  7     errors is specified, then the object must expose a data buffer
  8     that will be decoded using the given encoding and error handler.
  9     Otherwise, returns the result of object.__str__() (if defined)
 10     or repr(object).
 11     encoding defaults to sys.getdefaultencoding().
 12     errors defaults to 'strict'.
 13     """
 14     def capitalize(self): # real signature unknown; restored from __doc__
 15         """
 16         首字母變大寫
 17         S.capitalize() -> str
 18 
 19         Return a capitalized version of S, i.e. make the first character
 20         have upper case and the rest lower case.
 21         """
 22         return ""
 23 
 24     def casefold(self): # real signature unknown; restored from __doc__
 25         """
 26         S.casefold() -> str
 27 
 28         Return a version of S suitable for caseless comparisons.
 29         """
 30         return ""
 31 
 32     def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
 33         """
 34         原來字符居中,不夠用空格補全
 35         S.center(width[, fillchar]) -> str
 36 
 37         Return S centered in a string of length width. Padding is
 38         done using the specified fill character (default is a space)
 39         """
 40         return ""
 41 
 42     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 43         """
 44          從一個範圍內的統計某str出現次數
 45         S.count(sub[, start[, end]]) -> int
 46 
 47         Return the number of non-overlapping occurrences of substring sub in
 48         string S[start:end].  Optional arguments start and end are
 49         interpreted as in slice notation.
 50         """
 51         return 0
 52 
 53     def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
 54         """
 55         encode(encoding='utf-8',errors='strict')
 56         以encoding指定編碼格式編碼,若是出錯默認報一個ValueError,除非errors指定的是
 57         ignore或replace
 58 
 59         S.encode(encoding='utf-8', errors='strict') -> bytes
 60 
 61         Encode S using the codec registered for encoding. Default encoding
 62         is 'utf-8'. errors may be given to set a different error
 63         handling scheme. Default is 'strict' meaning that encoding errors raise
 64         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 65         'xmlcharrefreplace' as well as any other name registered with
 66         codecs.register_error that can handle UnicodeEncodeErrors.
 67         """
 68         return b""
 69 
 70     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
 71         """
 72         S.endswith(suffix[, start[, end]]) -> bool
 73 
 74         Return True if S ends with the specified suffix, False otherwise.
 75         With optional start, test S beginning at that position.
 76         With optional end, stop comparing S at that position.
 77         suffix can also be a tuple of strings to try.
 78         """
 79         return False
 80 
 81     def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
 82         """
 83         將字符串中包含的\t轉換成tabsize個空格
 84         S.expandtabs(tabsize=8) -> str
 85 
 86         Return a copy of S where all tab characters are expanded using spaces.
 87         If tabsize is not given, a tab size of 8 characters is assumed.
 88         """
 89         return ""
 90 
 91     def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 92         """
 93         S.find(sub[, start[, end]]) -> int
 94 
 95         Return the lowest index in S where substring sub is found,
 96         such that sub is contained within S[start:end].  Optional
 97         arguments start and end are interpreted as in slice notation.
 98 
 99         Return -1 on failure.
100         """
101         return 0
102 
103     def format(self, *args, **kwargs): # known special case of str.format
104         """
105         格式化輸出
106         三種形式:
107         形式一.
108         >>> print('{0}{1}{0}'.format('a','b'))
109         aba
110 
111         形式二:(必須一一對應)
112         >>> print('{}{}{}'.format('a','b'))
113         Traceback (most recent call last):
114           File "<input>", line 1, in <module>
115         IndexError: tuple index out of range
116         >>> print('{}{}'.format('a','b'))
117         ab
118 
119         形式三:
120         >>> print('{name} {age}'.format(age=12,name='lhf'))
121         lhf 12
122 
123         S.format(*args, **kwargs) -> str
124 
125         Return a formatted version of S, using substitutions from args and kwargs.
126         The substitutions are identified by braces ('{' and '}').
127         """
128         pass
129 
130     def format_map(self, mapping): # real signature unknown; restored from __doc__
131         """
132         與format區別
133         '{name}'.format(**dict(name='alex'))
134         '{name}'.format_map(dict(name='alex'))
135 
136         S.format_map(mapping) -> str
137 
138         Return a formatted version of S, using substitutions from mapping.
139         The substitutions are identified by braces ('{' and '}').
140         """
141         return ""
142 
143     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
144         """
145         S.index(sub[, start[, end]]) -> int
146 
147         Like S.find() but raise ValueError when the substring is not found.
148         """
149         return 0
150 
151     def isalnum(self): # real signature unknown; restored from __doc__
152         """
153         至少一個字符,且都是字母或數字才返回True
154 
155         S.isalnum() -> bool
156 
157         Return True if all characters in S are alphanumeric
158         and there is at least one character in S, False otherwise.
159         """
160         return False
161 
162     def isalpha(self): # real signature unknown; restored from __doc__
163         """
164         至少一個字符,且都是字母才返回True
165         S.isalpha() -> bool
166 
167         Return True if all characters in S are alphabetic
168         and there is at least one character in S, False otherwise.
169         """
170         return False
171 
172     def isdecimal(self): # real signature unknown; restored from __doc__
173         """
174         S.isdecimal() -> bool
175 
176         Return True if there are only decimal characters in S,
177         False otherwise.
178         """
179         return False
180 
181     def isdigit(self): # real signature unknown; restored from __doc__
182         """
183         S.isdigit() -> bool
184 
185         Return True if all characters in S are digits
186         and there is at least one character in S, False otherwise.
187         """
188         return False
189 
190     def isidentifier(self): # real signature unknown; restored from __doc__
191         """
192         字符串爲關鍵字返回True
193 
194         S.isidentifier() -> bool
195 
196         Return True if S is a valid identifier according
197         to the language definition.
198 
199         Use keyword.iskeyword() to test for reserved identifiers
200         such as "def" and "class".
201         """
202         return False
203 
204     def islower(self): # real signature unknown; restored from __doc__
205         """
206         至少一個字符,且都是小寫字母才返回True
207         S.islower() -> bool
208 
209         Return True if all cased characters in S are lowercase and there is
210         at least one cased character in S, False otherwise.
211         """
212         return False
213 
214     def isnumeric(self): # real signature unknown; restored from __doc__
215         """
216         S.isnumeric() -> bool
217 
218         Return True if there are only numeric characters in S,
219         False otherwise.
220         """
221         return False
222 
223     def isprintable(self): # real signature unknown; restored from __doc__
224         """
225         S.isprintable() -> bool
226 
227         Return True if all characters in S are considered
228         printable in repr() or S is empty, False otherwise.
229         """
230         return False
231 
232     def isspace(self): # real signature unknown; restored from __doc__
233         """
234         至少一個字符,且都是空格才返回True
235         S.isspace() -> bool
236 
237         Return True if all characters in S are whitespace
238         and there is at least one character in S, False otherwise.
239         """
240         return False
241 
242     def istitle(self): # real signature unknown; restored from __doc__
243         """
244         >>> a='Hello'
245         >>> a.istitle()
246         True
247         >>> a='HellP'
248         >>> a.istitle()
249         False
250 
251         S.istitle() -> bool
252 
253         Return True if S is a titlecased string and there is at least one
254         character in S, i.e. upper- and titlecase characters may only
255         follow uncased characters and lowercase characters only cased ones.
256         Return False otherwise.
257         """
258         return False
259 
260     def isupper(self): # real signature unknown; restored from __doc__
261         """
262         S.isupper() -> bool
263 
264         Return True if all cased characters in S are uppercase and there is
265         at least one cased character in S, False otherwise.
266         """
267         return False
268 
269     def join(self, iterable): # real signature unknown; restored from __doc__
270         """
271         #對序列進行操做(分別使用' '與':'做爲分隔符)
272         >>> seq1 = ['hello','good','boy','doiido']
273         >>> print ' '.join(seq1)
274         hello good boy doiido
275         >>> print ':'.join(seq1)
276         hello:good:boy:doiido
277 
278 
279         #對字符串進行操做
280 
281         >>> seq2 = "hello good boy doiido"
282         >>> print ':'.join(seq2)
283         h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
284 
285 
286         #對元組進行操做
287 
288         >>> seq3 = ('hello','good','boy','doiido')
289         >>> print ':'.join(seq3)
290         hello:good:boy:doiido
291 
292 
293         #對字典進行操做
294 
295         >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
296         >>> print ':'.join(seq4)
297         boy:good:doiido:hello
298 
299 
300         #合併目錄
301 
302         >>> import os
303         >>> os.path.join('/hello/','good/boy/','doiido')
304         '/hello/good/boy/doiido'
305 
306 
307         S.join(iterable) -> str
308 
309         Return a string which is the concatenation of the strings in the
310         iterable.  The separator between elements is S.
311         """
312         return ""
313 
314     def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
315         """
316         S.ljust(width[, fillchar]) -> str
317 
318         Return S left-justified in a Unicode string of length width. Padding is
319         done using the specified fill character (default is a space).
320         """
321         return ""
322 
323     def lower(self): # real signature unknown; restored from __doc__
324         """
325         S.lower() -> str
326 
327         Return a copy of the string S converted to lowercase.
328         """
329         return ""
330 
331     def lstrip(self, chars=None): # real signature unknown; restored from __doc__
332         """
333         S.lstrip([chars]) -> str
334 
335         Return a copy of the string S with leading whitespace removed.
336         If chars is given and not None, remove characters in chars instead.
337         """
338         return ""
339 
340     def maketrans(self, *args, **kwargs): # real signature unknown
341         """
342         Return a translation table usable for str.translate().
343 
344         If there is only one argument, it must be a dictionary mapping Unicode
345         ordinals (integers) or characters to Unicode ordinals, strings or None.
346         Character keys will be then converted to ordinals.
347         If there are two arguments, they must be strings of equal length, and
348         in the resulting dictionary, each character in x will be mapped to the
349         character at the same position in y. If there is a third argument, it
350         must be a string, whose characters will be mapped to None in the result.
351         """
352         pass
353 
354     def partition(self, sep): # real signature unknown; restored from __doc__
355         """
356         以sep爲分割,將S分紅head,sep,tail三部分
357 
358         S.partition(sep) -> (head, sep, tail)
359 
360         Search for the separator sep in S, and return the part before it,
361         the separator itself, and the part after it.  If the separator is not
362         found, return S and two empty strings.
363         """
364         pass
365 
366     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
367         """
368         S.replace(old, new[, count]) -> str
369 
370         Return a copy of S with all occurrences of substring
371         old replaced by new.  If the optional argument count is
372         given, only the first count occurrences are replaced.
373         """
374         return ""
375 
376     def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
377         """
378         S.rfind(sub[, start[, end]]) -> int
379 
380         Return the highest index in S where substring sub is found,
381         such that sub is contained within S[start:end].  Optional
382         arguments start and end are interpreted as in slice notation.
383 
384         Return -1 on failure.
385         """
386         return 0
387 
388     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
389         """
390         S.rindex(sub[, start[, end]]) -> int
391 
392         Like S.rfind() but raise ValueError when the substring is not found.
393         """
394         return 0
395 
396     def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
397         """
398         S.rjust(width[, fillchar]) -> str
399 
400         Return S right-justified in a string of length width. Padding is
401         done using the specified fill character (default is a space).
402         """
403         return ""
404 
405     def rpartition(self, sep): # real signature unknown; restored from __doc__
406         """
407         S.rpartition(sep) -> (head, sep, tail)
408 
409         Search for the separator sep in S, starting at the end of S, and return
410         the part before it, the separator itself, and the part after it.  If the
411         separator is not found, return two empty strings and S.
412         """
413         pass
414 
415     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
416         """
417         S.rsplit(sep=None, maxsplit=-1) -> list of strings
418 
419         Return a list of the words in S, using sep as the
420         delimiter string, starting at the end of the string and
421         working to the front.  If maxsplit is given, at most maxsplit
422         splits are done. If sep is not specified, any whitespace string
423         is a separator.
424         """
425         return []
426 
427     def rstrip(self, chars=None): # real signature unknown; restored from __doc__
428         """
429         S.rstrip([chars]) -> str
430 
431         Return a copy of the string S with trailing whitespace removed.
432         If chars is given and not None, remove characters in chars instead.
433         """
434         return ""
435 
436     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
437         """
438         以sep爲分割,將S切分紅列表,與partition的區別在於切分結果不包含sep,
439         若是一個字符串中包含多個sep那麼maxsplit爲最多切分紅幾部分
440         >>> a='a,b c\nd\te'
441         >>> a.split()
442         ['a,b', 'c', 'd', 'e']
443         S.split(sep=None, maxsplit=-1) -> list of strings
444 
445         Return a list of the words in S, using sep as the
446         delimiter string.  If maxsplit is given, at most maxsplit
447         splits are done. If sep is not specified or is None, any
448         whitespace string is a separator and empty strings are
449         removed from the result.
450         """
451         return []
452 
453     def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
454         """
455         Python splitlines() 按照行('\r', '\r\n', \n')分隔,
456         返回一個包含各行做爲元素的列表,若是參數 keepends 爲 False,不包含換行符,如        果爲 True,則保留換行符。
457         >>> x
458         'adsfasdf\nsadf\nasdf\nadf'
459         >>> x.splitlines()
460         ['adsfasdf', 'sadf', 'asdf', 'adf']
461         >>> x.splitlines(True)
462         ['adsfasdf\n', 'sadf\n', 'asdf\n', 'adf']
463 
464         S.splitlines([keepends]) -> list of strings
465 
466         Return a list of the lines in S, breaking at line boundaries.
467         Line breaks are not included in the resulting list unless keepends
468         is given and true.
469         """
470         return []
471 
472     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
473         """
474         S.startswith(prefix[, start[, end]]) -> bool
475 
476         Return True if S starts with the specified prefix, False otherwise.
477         With optional start, test S beginning at that position.
478         With optional end, stop comparing S at that position.
479         prefix can also be a tuple of strings to try.
480         """
481         return False
482 
483     def strip(self, chars=None): # real signature unknown; restored from __doc__
484         """
485         S.strip([chars]) -> str
486 
487         Return a copy of the string S with leading and trailing
488         whitespace removed.
489         If chars is given and not None, remove characters in chars instead.
490         """
491         return ""
492 
493     def swapcase(self): # real signature unknown; restored from __doc__
494         """
495         大小寫反轉
496         S.swapcase() -> str
497 
498         Return a copy of S with uppercase characters converted to lowercase
499         and vice versa.
500         """
501         return ""
502 
503     def title(self): # real signature unknown; restored from __doc__
504         """
505         S.title() -> str
506 
507         Return a titlecased version of S, i.e. words start with title case
508         characters, all remaining cased characters have lower case.
509         """
510         return ""
511 
512     def translate(self, table): # real signature unknown; restored from __doc__
513         """
514         table=str.maketrans('alex','big SB')
515 
516         a='hello abc'
517         print(a.translate(table))
518 
519         S.translate(table) -> str
520 
521         Return a copy of the string S in which each character has been mapped
522         through the given translation table. The table must implement
523         lookup/indexing via __getitem__, for instance a dictionary or list,
524         mapping Unicode ordinals to Unicode ordinals, strings, or None. If
525         this operation raises LookupError, the character is left untouched.
526         Characters mapped to None are deleted.
527         """
528         return ""
529 
530     def upper(self): # real signature unknown; restored from __doc__
531         """
532         S.upper() -> str
533 
534         Return a copy of S converted to uppercase.
535         """
536         return ""
537 
538     def zfill(self, width): # real signature unknown; restored from __doc__
539         """
540         原來字符右對齊,不夠用0補齊
541         
542         S.zfill(width) -> str
543 
544         Pad a numeric string S with zeros on the left, to fill a field
545         of the specified width. The string S is never truncated.
546         """
547         return ""
548 
549     def __add__(self, *args, **kwargs): # real signature unknown
550         """ Return self+value. """
551         pass
552 
553     def __contains__(self, *args, **kwargs): # real signature unknown
554         """ Return key in self. """
555         pass
556 
557     def __eq__(self, *args, **kwargs): # real signature unknown
558         """ Return self==value. """
559         pass
560 
561     def __format__(self, format_spec): # real signature unknown; restored from __doc__
562         """
563         S.__format__(format_spec) -> str
564 
565         Return a formatted version of S as described by format_spec.
566         """
567         return ""
568 
569     def __getattribute__(self, *args, **kwargs): # real signature unknown
570         """ Return getattr(self, name). """
571         pass
572 
573     def __getitem__(self, *args, **kwargs): # real signature unknown
574         """ Return self[key]. """
575         pass
576 
577     def __getnewargs__(self, *args, **kwargs): # real signature unknown
578         pass
579 
580     def __ge__(self, *args, **kwargs): # real signature unknown
581         """ Return self>=value. """
582         pass
583 
584     def __gt__(self, *args, **kwargs): # real signature unknown
585         """ Return self>value. """
586         pass
587 
588     def __hash__(self, *args, **kwargs): # real signature unknown
589         """ Return hash(self). """
590         pass
591 
592     def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
593         """
594         str(object='') -> str
595         str(bytes_or_buffer[, encoding[, errors]]) -> str
596 
597         Create a new string object from the given object. If encoding or
598         errors is specified, then the object must expose a data buffer
599         that will be decoded using the given encoding and error handler.
600         Otherwise, returns the result of object.__str__() (if defined)
601         or repr(object).
602         encoding defaults to sys.getdefaultencoding().
603         errors defaults to 'strict'.
604         # (copied from class doc)
605         """
606         pass
607 
608     def __iter__(self, *args, **kwargs): # real signature unknown
609         """ Implement iter(self). """
610         pass
611 
612     def __len__(self, *args, **kwargs): # real signature unknown
613         """ Return len(self). """
614         pass
615 
616     def __le__(self, *args, **kwargs): # real signature unknown
617         """ Return self<=value. """
618         pass
619 
620     def __lt__(self, *args, **kwargs): # real signature unknown
621         """ Return self<value. """
622         pass
623 
624     def __mod__(self, *args, **kwargs): # real signature unknown
625         """ Return self%value. """
626         pass
627 
628     def __mul__(self, *args, **kwargs): # real signature unknown
629         """ Return self*value.n """
630         pass
631 
632     @staticmethod # known case of __new__
633     def __new__(*args, **kwargs): # real signature unknown
634         """ Create and return a new object.  See help(type) for accurate signature. """
635         pass
636 
637     def __ne__(self, *args, **kwargs): # real signature unknown
638         """ Return self!=value. """
639         pass
640 
641     def __repr__(self, *args, **kwargs): # real signature unknown
642         """ Return repr(self). """
643         pass
644 
645     def __rmod__(self, *args, **kwargs): # real signature unknown
646         """ Return value%self. """
647         pass
648 
649     def __rmul__(self, *args, **kwargs): # real signature unknown
650         """ Return self*value. """
651         pass
652 
653     def __sizeof__(self): # real signature unknown; restored from __doc__
654         """ S.__sizeof__() -> size of S in memory, in bytes """
655         pass
656 
657     def __str__(self, *args, **kwargs): # real signature unknown
658         """ Return str(self). """
659         pass
660 
661 字符串工廠函數
662 
663 字符串工廠函數
View Code

 

2.2.2.4 經常使用舉例

s.strip()
s.split()
s.find() #搜索,索引或-1
s.index() #搜索,可是報錯
s.count()
s.replace()
s.startwith()
s.endwith()
s.isdigit()
s[1:5:2]

 

# -*-coding:UTF-8-*-



# 字符串:
#補充
# x='a' #x=str('a')  字符串操做本質上都是調用str()
# x.replace ===>  str.replace()

'''
#字符串類型:引號包含的都是字符串類型
#須要掌握的經常使用操做:

msg='hello'
移除空白 msg.strip()
分割msg.split('|')
長度len(msg)
索引msg[3] msg[-1]
切片msg[0:5:2]  #0  2  4
'''

# 字符串
# s='hello world'
# s1="hello world"
# s2="""hello world"""
# s3='''hello world'''
# print(type(s))
# print(type(s1))
# print(type(s2))
# print(type(s3))

'''
# x='*****egon********'
# x=x.strip()      #strip()方法用於移除字符串頭尾指定的字符(默認爲空格)。
# print(x)
# print(x.strip('*'))
'''

#首字母大寫
# x='hello'
# print(x.capitalize())

'''
#全部字母大寫
# x='hello'
# print(x.upper())
'''

# #居中顯示
# x='hello'
# print(x.center(30,'#'))

'''
#統計某個字符的長度,空格也算字符
# x='hel lo love'
# print(x.count('l'))
# print(x.count('l',0,4)) # 0 1 2 3
'''

# x='hello '                #開始的字符、末尾的字符分別是什麼
# print(x.endswith(' '))
# print(x.startswith('h'))

'''
# x='hello '                #find() 方法檢測字符串中是否包含子字符串 str ,
# print(x.find('e'))        #若是指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,
# print(x.find('l'))        #若是包含子字符串返回開始的索引值,不然返回-1。
'''

# 格式化字符串
# msg='Name:{},age:{},sex:{}'
# print(msg) #Name:{},age:{},sex:{}
# print(msg.format('egon',18,'male'))

# msg='Name:{0},age:{1},sex:{0}'
# print(msg.format('aaaaaaaaaaaaaaaaa','bbbbbbbbbbbbbb'))

# msg='Name:{x},age:{y},sex:{z}'
# print(msg.format(y=18,x='egon',z='male'))


'''
# x='hello world'
# print(x[0])
# print(x[4])
# print(x[5])
# print(x[100]) #報錯

# print(x[-1])
# print(x[-3])
# print(x[1:3])
# print(x[1:5:2])   #始 末 步長
'''

# x='hello'                  #方法檢測字符串中是否包含子字符串 str ,
# print(x.index('o'))        #若是指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,
# print(x[4])                #該方法與 python find()方法同樣,只不過若是str不在 string中會報一個異常。
# print(x[x.index('o')])

'''
# x='123'
# print(x.isdigit())         #檢測字符串是否只由數字組成。
#
# age=input('age: ')
# if age.isdigit():
#     new_age=int(age)
#     print(new_age,type(new_age))
'''


# msg='hello alex'
# print(msg.replace('x','X'))
# print(msg.replace('alex','SB'))
# print(msg.replace('l','A'))
# print(msg.replace('l','A',1))    #替換一個
# print(msg.replace('l','A',2))    #替換兩個

'''
# x='hello          world alex SB'
# x='root:x:0:0::/root:/bin/bash'
# print(x.split(':'))
# split()經過指定分隔符對字符串進行切片,若是參數num 有指定值,則僅分隔 num 個子字符串
# 語法:str.split(str="", num=string.count(str)).
# num是指切幾回,切出幾個
'''

# x='hello'
# # print(x.upper())    #所有變成大寫
# x='H'
# print(x.isupper())    #是不是大寫
# x='HELLO'
# print(x.islower())    #是不是小寫
# print(x.lower())      #所有變成小寫

# x='     '
# print(x.isspace())    #是否全是空格

# msg='Hello'
# msg='hEEEE'
# print(msg.istitle())   #首字母大寫/字符串中全部的單詞拼寫首字母是否爲大寫,且其餘字母爲小寫。
#
# x='hello'
# print(x.title())       #首字母大寫

# x='abc'
# print(x.ljust(10,'*'))
# print(x.rjust(10,'*'))
# ljust() 方法返回一個原字符串左對齊,並使用空格填充至指定長度的新字符串。若是指定的長度小於原字符串的長度則返回原字符串。
# 語法:str.ljust(width[, fillchar])
# rjust是右對齊

# x='Ab'
# print(x.swapcase())   #對字符串的大小寫字母進行轉換。 
View Code

 

2.2.3 列表

 

列表之間能夠比較大小,從第一個元素開始比較,只要這個元素可以分出大小就結束

 

定義:[]內以逗號分隔,按照索引,存放各類數據類型,每一個位置表明一個元素
特性:
1.可存放多個值
2.可修改指定索引位置對應的值,可變
3.
按照從左到右的順序定義列表元素,下標從0開始順序訪問,有序

2.2.3.1 列表建立

list_test=[’lhf‘,12,'ok']

list_test=list('abc')

list_test=list([’lhf‘,12,'ok'])

2.2.3.2 列表經常使用操做

索引
切片
追加
刪除
長度
切片
循環
包含

 

2.2.4 元組

定義:與列表相似,只不過[]改爲()
特性:
1.可存放多個值
2.不可變
3.
按照從左到右的順序定義元組元素,下標從0開始順序訪問,有序

2.2.4.1 元組建立

ages = (11, 22, 33, 44, 55)

ages = tuple((11, 22, 33, 44, 55))

2.2.4.2 元組經常使用操做

索引
切片
循環
長度
包含

2.2.4.3 元組工廠函數tuple()

2.2.5 字典

定義:{key1:value1,key2:value2},key-value結構,key必須可hash
特性:
1.可存放多個值
2.可修改指定key對應的值,可變
3.無

2.2.5.1 字典建立

person = {"name": "sb", 'age': 18}

person = dict(name='sb', age=18)
person = dict({"name": "sb", 'age': 18})
person = dict((['name','sb'],['age',18]))
{}.fromkeys(seq,100) #不指定100默認爲None
注意:
>>> dic={}.fromkeys(['k1','k2'],[])
>>> dic
{'k1': [], 'k2': []}
>>> dic['k1'].append(1)
>>> dic
{'k1': [1], 'k2': [1]} 

2.2.5.2 字典經常使用操做

索引
新增
刪除
鍵、值、鍵值對
循環
長度

2.2.5.3 字典工廠函數dict()

2.2.6 集合

定義:由不一樣元素組成的集合,集合中是一組無序排列的可hash值,能夠做爲字典的key
特性:
1.集合的目的是將不一樣的值存放到一塊兒,不一樣的集合間用來作關係運算,無需糾結於集合中單個值

2.2.6.1 集合建立

{1,2,3,1}

定義可變集合set
>>> set_test=set('hello')
>>> set_test
{'l', 'o', 'e', 'h'}
改成不可變集合frozenset
>>> f_set_test=frozenset(set_test)
>>> f_set_test
frozenset({'l', 'e', 'h', 'o'})

2.2.6.2 集合經常使用操做:關係運算

   in
not in
==
!=
<,<=
>,>=
|,|=:合集
&.&=:交集
-,-=:差集
^,^=:對稱差分

2.2.7 bytes類型

定義:存8bit整數,數據基於網絡傳輸或內存變量存儲到硬盤時須要轉成bytes類型,字符串前置b表明爲bytes類型

>>> x
'hello sb'
>>> x.encode('gb2312')
b'hello sb'

2.2.8 數據類型轉換內置函數彙總

注:真對acsii表unichr在python2.7中比chr的範圍更大,python3.*中chr內置了unichar

 

三 算數運算;邏輯運算;比較運算;關係運算;

四.標準數據類型特性總結

按存值個數區分

標量/原子類型 數字,字符串
容器類型 列表,元組,字典

 

 

按可變不可變區分

可變 列表,字典
不可變 數字,字符串,元組

 

 

按訪問順序區分

直接訪問 數字
順序訪問(序列類型) 字符串,列表,元組
key值訪問(映射類型) 字典
相關文章
相關標籤/搜索