Python高手之路【二】python基本数据类型
一:數字 int
int(整型):
在32位機器上,整數的位數為32位,取值范圍為-2**31~2**31-1,即-2147483648~2147483647
在64位系統上,整數的位數為64位,取值范圍為-2**63~2**63-1,即-9223372036854775808~9223372036854775807
long(長整型):
跟C語言不同,Python的長整數沒有指定位寬,即:Python沒有限制長整數數值的大小,但實際上由于機器內存有限,我們使用的長整數數值不可能無限大
注意:自從python2.2起,如果整數發生溢出,python會自動將整數數據轉換為長整數,所以如今在長整數數據后面不加字母L也不會導致嚴重后果了
float(浮點型):
浮點數用來處理實數,即帶有小數的數字,類似于C語言中的double類型,占8個字節(64位),其中52位表示底,11位表示指數,剩下一位表示符號
class int(object):"""int(x=0) -> int or longint(x, base=10) -> int or longConvert a number or string to an integer, or return 0 if no argumentsare given. If x is floating point, the conversion truncates towards zero.If x is outside the integer range, the function returns a long instead.If x is not a number or if base is given, then x must be a string orUnicode object representing an integer literal in the given base. Theliteral can be preceded by '+' or '-' and be surrounded by whitespace.The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means tointerpret the base from the string as an integer literal.>>> int('0b100', base=0)"""def bit_length(self): """ 返回表示該數字的時占用的最少位數 """"""int.bit_length() -> intNumber of bits necessary to represent self in binary.>>> bin(37)'0b100101'>>> (37).bit_length()"""return 0def conjugate(self, *args, **kwargs): # real signature unknown""" 返回該復數的共軛復數 """""" Returns self, the complex conjugate of any int. """passdef __abs__(self):""" 返回絕對值 """""" x.__abs__() <==> abs(x) """passdef __add__(self, y):""" x.__add__(y) <==> x+y """passdef __and__(self, y):""" x.__and__(y) <==> x&y """passdef __cmp__(self, y): """ 比較兩個數大小 """""" x.__cmp__(y) <==> cmp(x,y) """passdef __coerce__(self, y):""" 強制生成一個元組 """ """ x.__coerce__(y) <==> coerce(x, y) """passdef __divmod__(self, y): """ 相除,得到商和余數組成的元組 """ """ x.__divmod__(y) <==> divmod(x, y) """passdef __div__(self, y): """ x.__div__(y) <==> x/y """passdef __float__(self): """ 轉換為浮點類型 """ """ x.__float__() <==> float(x) """passdef __floordiv__(self, y): """ x.__floordiv__(y) <==> x//y """passdef __format__(self, *args, **kwargs): # real signature unknownpassdef __getattribute__(self, name): """ x.__getattribute__('name') <==> x.name """passdef __getnewargs__(self, *args, **kwargs): # real signature unknown""" 內部調用 __new__方法或創建對象時傳入參數使用 """ passdef __hash__(self): """如果對象object為哈希表類型,返回對象object的哈希值。哈希值為整數。在字典查找中,哈希值用于快速比較字典的鍵。兩個數值如果相等,則哈希值也相等。"""""" x.__hash__() <==> hash(x) """passdef __hex__(self): """ 返回當前數的 十六進制 表示 """ """ x.__hex__() <==> hex(x) """passdef __index__(self): """ 用于切片,數字無意義 """""" x[y:z] <==> x[y.__index__():z.__index__()] """passdef __init__(self, x, base=10): # known special case of int.__init__""" 構造方法,執行 x = 123 或 x = int(10) 時,自動調用,暫時忽略 """ """int(x=0) -> int or longint(x, base=10) -> int or longConvert a number or string to an integer, or return 0 if no argumentsare given. If x is floating point, the conversion truncates towards zero.If x is outside the integer range, the function returns a long instead.If x is not a number or if base is given, then x must be a string orUnicode object representing an integer literal in the given base. Theliteral can be preceded by '+' or '-' and be surrounded by whitespace.The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means tointerpret the base from the string as an integer literal.>>> int('0b100', base=0)# (copied from class doc)"""passdef __int__(self): """ 轉換為整數 """ """ x.__int__() <==> int(x) """passdef __invert__(self): """ x.__invert__() <==> ~x """passdef __long__(self): """ 轉換為長整數 """ """ x.__long__() <==> long(x) """passdef __lshift__(self, y): """ x.__lshift__(y) <==> x<<y """passdef __mod__(self, y): """ x.__mod__(y) <==> x%y """passdef __mul__(self, y): """ x.__mul__(y) <==> x*y """passdef __neg__(self): """ x.__neg__() <==> -x """pass@staticmethod # known case of __new__def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __nonzero__(self): """ x.__nonzero__() <==> x != 0 """passdef __oct__(self): """ 返回改值的 八進制 表示 """ """ x.__oct__() <==> oct(x) """passdef __or__(self, y): """ x.__or__(y) <==> x|y """passdef __pos__(self): """ x.__pos__() <==> +x """passdef __pow__(self, y, z=None): """ 冪,次方 """ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """passdef __radd__(self, y): """ x.__radd__(y) <==> y+x """passdef __rand__(self, y): """ x.__rand__(y) <==> y&x """passdef __rdivmod__(self, y): """ x.__rdivmod__(y) <==> divmod(y, x) """passdef __rdiv__(self, y): """ x.__rdiv__(y) <==> y/x """passdef __repr__(self): """轉化為解釋器可讀取的形式 """""" x.__repr__() <==> repr(x) """passdef __str__(self): """轉換為人閱讀的形式,如果沒有適于人閱讀的解釋形式的話,則返回解釋器課閱讀的形式"""""" x.__str__() <==> str(x) """passdef __rfloordiv__(self, y): """ x.__rfloordiv__(y) <==> y//x """passdef __rlshift__(self, y): """ x.__rlshift__(y) <==> y<<x """passdef __rmod__(self, y): """ x.__rmod__(y) <==> y%x """passdef __rmul__(self, y): """ x.__rmul__(y) <==> y*x """passdef __ror__(self, y): """ x.__ror__(y) <==> y|x """passdef __rpow__(self, x, z=None): """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """passdef __rrshift__(self, y): """ x.__rrshift__(y) <==> y>>x """passdef __rshift__(self, y): """ x.__rshift__(y) <==> x>>y """passdef __rsub__(self, y): """ x.__rsub__(y) <==> y-x """passdef __rtruediv__(self, y): """ x.__rtruediv__(y) <==> y/x """passdef __rxor__(self, y): """ x.__rxor__(y) <==> y^x """passdef __sub__(self, y): """ x.__sub__(y) <==> x-y """passdef __truediv__(self, y): """ x.__truediv__(y) <==> x/y """passdef __trunc__(self, *args, **kwargs): """ 返回數值被截取為整形的值,在整形中無意義 """passdef __xor__(self, y): """ x.__xor__(y) <==> x^y """passdenominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default""" 分母 = 1 """"""the denominator of a rational number in lowest terms"""imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default""" 虛數,無意義 """"""the imaginary part of a complex number"""numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default""" 分子 = 數字大小 """"""the numerator of a rational number in lowest terms"""real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default""" 實屬,無意義 """"""the real part of a complex number"""int int二:字符串 str
class str(basestring):"""str(object='') -> stringReturn a nice string representation of the object.If the argument is a string, the return value is the same object."""def capitalize(self): """ 首字母變大寫 """"""S.capitalize() -> stringReturn a copy of the string S with only its first charactercapitalized."""return ""def center(self, width, fillchar=None): """ 內容居中,width:總長度;fillchar:空白處填充內容,默認無 """"""S.center(width[, fillchar]) -> stringReturn S centered in a string of length width. Padding isdone using the specified fill character (default is a space)"""return ""def count(self, sub, start=None, end=None): """ 子序列個數 """"""S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end]. Optional arguments start and end are interpretedas in slice notation."""return 0def decode(self, encoding=None, errors=None): """ 解碼 """"""S.decode([encoding[,errors]]) -> objectDecodes S using the codec registered for encoding. encoding defaultsto the default encoding. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeDecodeError. Other possible values are 'ignore' and 'replace'as well as any other name registered with codecs.register_error that isable to handle UnicodeDecodeErrors."""return object()def encode(self, encoding=None, errors=None): """ 編碼,針對unicode """"""S.encode([encoding[,errors]]) -> objectEncodes S using the codec registered for encoding. encoding defaultsto the default encoding. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeEncodeError. Other possible values are 'ignore', 'replace' and'xmlcharrefreplace' as well as any other name registered withcodecs.register_error that is able to handle UnicodeEncodeErrors."""return object()def endswith(self, suffix, start=None, end=None): """ 是否以 xxx 結束 """"""S.endswith(suffix[, start[, end]]) -> boolReturn True if S ends with the specified suffix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.suffix can also be a tuple of strings to try."""return Falsedef expandtabs(self, tabsize=None): """ 將tab轉換成空格,默認一個tab轉換成8個空格 """"""S.expandtabs([tabsize]) -> stringReturn a copy of S where all tab characters are expanded using spaces.If tabsize is not given, a tab size of 8 characters is assumed."""return ""def find(self, sub, start=None, end=None): """ 尋找子序列位置,如果沒找到,返回 -1 """"""S.find(sub [,start [,end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0def format(*args, **kwargs): # known special case of str.format""" 字符串格式化,動態參數,將函數式編程時細說 """"""S.format(*args, **kwargs) -> stringReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}')."""passdef index(self, sub, start=None, end=None): """ 子序列位置,如果沒找到,報錯 """S.index(sub [,start [,end]]) -> intLike S.find() but raise ValueError when the substring is not found."""return 0def isalnum(self): """ 是否是字母和數字 """"""S.isalnum() -> boolReturn True if all characters in S are alphanumericand there is at least one character in S, False otherwise."""return Falsedef isalpha(self): """ 是否是字母 """"""S.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise."""return Falsedef isdigit(self): """ 是否是數字 """"""S.isdigit() -> boolReturn True if all characters in S are digitsand there is at least one character in S, False otherwise."""return Falsedef islower(self): """ 是否小寫 """"""S.islower() -> boolReturn True if all cased characters in S are lowercase and there isat least one cased character in S, False otherwise."""return Falsedef isspace(self): """S.isspace() -> boolReturn True if all characters in S are whitespaceand there is at least one character in S, False otherwise."""return Falsedef istitle(self): """S.istitle() -> boolReturn True if S is a titlecased string and there is at least onecharacter in S, i.e. uppercase characters may only follow uncasedcharacters and lowercase characters only cased ones. Return Falseotherwise."""return Falsedef isupper(self): """S.isupper() -> boolReturn True if all cased characters in S are uppercase and there isat least one cased character in S, False otherwise."""return Falsedef join(self, iterable): """ 連接 """"""S.join(iterable) -> stringReturn a string which is the concatenation of the strings in theiterable. The separator between elements is S."""return ""def ljust(self, width, fillchar=None): """ 內容左對齊,右側填充 """"""S.ljust(width[, fillchar]) -> stringReturn S left-justified in a string of length width. Padding isdone using the specified fill character (default is a space)."""return ""def lower(self): """ 變小寫 """"""S.lower() -> stringReturn a copy of the string S converted to lowercase."""return ""def lstrip(self, chars=None): """ 移除左側空白 """"""S.lstrip([chars]) -> string or unicodeReturn a copy of the string S with leading whitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def partition(self, sep): """ 分割,前,中,后三部分 """"""S.partition(sep) -> (head, sep, tail)Search for the separator sep in S, and return the part before it,the separator itself, and the part after it. If the separator is notfound, return S and two empty strings."""passdef replace(self, old, new, count=None): """ 替換 """"""S.replace(old, new[, count]) -> stringReturn a copy of string S with all occurrences of substringold replaced by new. If the optional argument count isgiven, only the first count occurrences are replaced."""return ""def rfind(self, sub, start=None, end=None): """S.rfind(sub [,start [,end]]) -> intReturn the highest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0def rindex(self, sub, start=None, end=None): """S.rindex(sub [,start [,end]]) -> intLike S.rfind() but raise ValueError when the substring is not found."""return 0def rjust(self, width, fillchar=None): """S.rjust(width[, fillchar]) -> stringReturn S right-justified in a string of length width. Padding isdone using the specified fill character (default is a space)"""return ""def rpartition(self, sep): """S.rpartition(sep) -> (head, sep, tail)Search for the separator sep in S, starting at the end of S, and returnthe part before it, the separator itself, and the part after it. If theseparator is not found, return two empty strings and S."""passdef rsplit(self, sep=None, maxsplit=None): """S.rsplit([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as thedelimiter string, starting at the end of the string and workingto the front. If maxsplit is given, at most maxsplit splits aredone. If sep is not specified or is None, any whitespace stringis a separator."""return []def rstrip(self, chars=None): """S.rstrip([chars]) -> string or unicodeReturn a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def split(self, sep=None, maxsplit=None): """ 分割, maxsplit最多分割幾次 """"""S.split([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as thedelimiter string. If maxsplit is given, at most maxsplitsplits are done. If sep is not specified or is None, anywhitespace string is a separator and empty strings are removedfrom the result."""return []def splitlines(self, keepends=False): """ 根據換行分割 """"""S.splitlines(keepends=False) -> list of stringsReturn a list of the lines in S, breaking at line boundaries.Line breaks are not included in the resulting list unless keependsis given and true."""return []def startswith(self, prefix, start=None, end=None): """ 是否起始 """"""S.startswith(prefix[, start[, end]]) -> boolReturn True if S starts with the specified prefix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.prefix can also be a tuple of strings to try."""return Falsedef strip(self, chars=None): """ 移除兩段空白 """"""S.strip([chars]) -> string or unicodeReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def swapcase(self): """ 大寫變小寫,小寫變大寫 """"""S.swapcase() -> stringReturn a copy of the string S with uppercase charactersconverted to lowercase and vice versa."""return ""def title(self): """S.title() -> stringReturn a titlecased version of S, i.e. words start with uppercasecharacters, all remaining cased characters have lowercase."""return ""def translate(self, table, deletechars=None): """轉換,需要先做一個對應表,最后一個表示刪除字符集合intab = "aeiou"outtab = "12345"trantab = maketrans(intab, outtab)str = "this is string example....wow!!!"print str.translate(trantab, 'xm')""""""S.translate(table [,deletechars]) -> stringReturn a copy of the string S, where all characters occurringin the optional argument deletechars are removed, and theremaining characters have been mapped through the giventranslation table, which must be a string of length 256 or None.If the table argument is None, no translation is applied andthe operation simply removes the characters in deletechars."""return ""def upper(self): """S.upper() -> stringReturn a copy of the string S converted to uppercase."""return ""def zfill(self, width): """方法返回指定長度的字符串,原字符串右對齊,前面填充0。""""""S.zfill(width) -> stringPad a numeric string S with zeros on the left, to fill a fieldof the specified width. The string S is never truncated."""return ""def _formatter_field_name_split(self, *args, **kwargs): # real signature unknownpassdef _formatter_parser(self, *args, **kwargs): # real signature unknownpassdef __add__(self, y): """ x.__add__(y) <==> x+y """passdef __contains__(self, y): """ x.__contains__(y) <==> y in x """passdef __eq__(self, y): """ x.__eq__(y) <==> x==y """passdef __format__(self, format_spec): """S.__format__(format_spec) -> stringReturn a formatted version of S as described by format_spec."""return ""def __getattribute__(self, name): """ x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): """ x.__getitem__(y) <==> x[y] """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __getslice__(self, i, j): """x.__getslice__(i, j) <==> x[i:j]Use of negative indices is not supported."""passdef __ge__(self, y): """ x.__ge__(y) <==> x>=y """passdef __gt__(self, y): """ x.__gt__(y) <==> x>y """passdef __hash__(self): """ x.__hash__() <==> hash(x) """passdef __init__(self, string=''): # known special case of str.__init__"""str(object='') -> stringReturn a nice string representation of the object.If the argument is a string, the return value is the same object.# (copied from class doc)"""passdef __len__(self): """ x.__len__() <==> len(x) """passdef __le__(self, y): """ x.__le__(y) <==> x<=y """passdef __lt__(self, y): """ x.__lt__(y) <==> x<y """passdef __mod__(self, y): """ x.__mod__(y) <==> x%y """passdef __mul__(self, n): """ x.__mul__(n) <==> x*n """pass@staticmethod # known case of __new__def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y): """ x.__ne__(y) <==> x!=y """passdef __repr__(self): """ x.__repr__() <==> repr(x) """passdef __rmod__(self, y): """ x.__rmod__(y) <==> y%x """passdef __rmul__(self, n): """ x.__rmul__(n) <==> n*x """passdef __sizeof__(self): """ S.__sizeof__() -> size of S in memory, in bytes """passdef __str__(self): """ x.__str__() <==> str(x) """passstr str?字符串是 Python 中最常用的數據類型。我們可以使用引號,雙引號,或三引號來創建字符串。
a = 'poe' b = "bruce" c = """Jacky Chen"""?1:字符串連接
方法一:join方法
1 a = ['a','b','c','d'] 2 content = '' 3 content = ' '.join(a) 4 print(content)方法二:用字符串的替換占位符替換
方法三:for循環
1 a = ['a','b','c','d'] 2 content = '' 3 for i in a: 4 content += i 5 print(content)注意:方法三效率低,不推薦使用!
原因:在循環連接字符串的時候,他每次連接一次,就要重新開辟空間,然后把字符串連接起來,再放入新的空間,再一次循環,又要開辟新的空間,把字符串連接起來放入新的空間,如此反復,內存操作比較頻繁,每次都要計算內存空間,然后開辟內存空間,再釋放內存空間,效率非常低,你也許操作比較少的數據的時候看不出來,感覺影響不大,但是你碰到操作數據量比較多的時候,這個方法就要退休了。
?2:字符串截取
我們可以通過索引來提取想要獲取的字符,可以把python的字符串也做為字符串的列表就更好理解
python的字串列表有2種取值順序:
1是從左到右索引默認0開始的,最大范圍是字符串長度少1
2是從右到左索引默認-1開始的,最大范圍是字符串開頭
s = 'ilovepython' s[-1]的結果是n上面這個是取得一個字符,如果你的實際要取得一段子串的話,可以用到變量[頭下標:尾下標],就可以截取相應的字符串,其中下標是從0開始算起,可以是正數或負數,下標可以為空表示取到頭或尾。
比如
s = 'ilovepython' s[1:5]的結果是love當使用以冒號分隔的字符串,python返回一個新的對象,結果包含了以這對偏移標識的連續的內容,左邊的開始是包含了下邊界,比如上面的結果包含了s[1]的值l,而取到的最大范圍不包括上邊界,就是s[5]的值p
注:s[1:5]形式截頭不截尾
3:字符串替換
方法一:使用repalce方法
1 a = 'hello world' 2 b = a.replace('world','python') 3 print(b)方法二:使用正則表達式
1 import re 2 a = 'hello world' 3 strinfo = re.compile('world') 4 b = strinfo.sub('python',a) 5 print(b)4:字符串比較
cmp方法比較兩個對象,并根據結果返回一個整數。cmp(x,y)如果X< Y,返回值是負數 如果X>Y 返回的值為正數。
1 str1 = 'strch' 2 str2 = 'strchr' 3 print(cmp(str1,str2)) 4 ## -15:字符串相加
我們通過操作符號+來進行字符串的相加,不過建議還是用其他的方式來進行字符串的拼接,這樣效率高點。
原因:在循環連接字符串的時候,他每次連接一次,就要重新開辟空間,然后把字符串連接起來,再放入新的空間,再一次循環,又要開辟新的空間,把字符串連接起來放入新的空間,如此反復,內存操作比較頻繁,每次都要計算內存空間,然后開辟內存空間,再釋放內存空間,效率非常低。
6:字符串查找
python 字符串查找有4個方法,1 find,2 index方法,3 rfind方法,4 rindex方法。
方法一:find方法
1 info = 'abca' 2 print info.find('a')##從下標0開始,查找在字符串里第一個出現的子串,返回結果:0 3 4 info = 'abca' 5 print info.find('a',1)##從下標1開始,查找在字符串里第一個出現的子串:返回結果3 6 7 info = 'abca' 8 print info.find('333')##返回-1,查找不到返回-1方法二:index方法
python 的index方法是在字符串里查找子串第一次出現的位置,類似字符串的find方法,不過比find方法更好的是,如果查找不到子串,會拋出異常,而不是返回-1
1 info = 'abca' 2 print info.index('a') 3 print info.index('33')7:字符串分割
字符串分割,可以用split,rsplit方法,通過相應的規則來切割成生成列表對象
1 info = 'name:haha,age:20$name:python,age:30$name:fef,age:55' 2 content = info.split('$') 3 print content 4 ## ['name:haha,age:20', 'name:python,age:30', 'name:fef,age:55']8:字符串反轉
1 a = 'abcd' 2 b = a[::-1]##[::-1]通過步進反轉 3 print b9:字符串編碼
?
10:字符串追加和拼接
通過字符串的占位符來進行字符串的拼接
#1 元組拼接 m = 'python' astr = 'i love %s' % m print astr#2 字符串的format方法 m = 'python' astr = "i love {python}".format(python=m) print astr#3 字典格式化字符串 m = 'python' astr = "i love %(python)s " % {'python':m} print astr11:字符串復制
#通過變量來進行賦值 fstr = 'strcpy' sstr = fstr fstr = 'strcpy2' print sstr12:字符串長度
#通過內置方法len()來計算字符串的長度,注意這個計算的是字符的長度。 aa = 'afebb' bb = '你' print len(aa) print len(bb)13:字符串大小寫
#通過下面的upper(),lower()等方法來轉換大小寫 S.upper()#S中的字母大寫 S.lower() #S中的字母小寫 S.capitalize() #首字母大寫 S.istitle() #S是否是首字母大寫的 S.isupper() #S中的字母是否便是大寫 S.islower() #S中的字母是否全是小寫14:字符串去空格
#通過strip(),lstrip(),rstrip()方法去除字符串的空格 S.strip() #去掉字符串的左右空格 S.lstrip() #去掉字符串的左邊空格 S.rstrip() #去掉字符串的右邊空格 #注意:strip()函數不僅可以去空格還可以去除指定的字符,如 S.strip("\n")15:字符串其他方法
#字符串相關的其他方法:count(),join()方法等。 S.center(width, [fillchar]) #中間對齊 S.count(substr, [start, [end]]) #計算substr在S中出現的次數 S.expandtabs([tabsize]) #把S中的tab字符替換沒空格,每個tab替換為tabsize個空格,默認是8個 S.isalnum() #是否全是字母和數字,并至少有一個字符 S.isalpha() #是否全是字母,并至少有一個字符 S.isspace() #是否全是空白字符,并至少有一個字符 S.join()#S中的join,把列表生成一個字符串對象 S.ljust(width,[fillchar]) #輸出width個字符,S左對齊,不足部分用fillchar填充,默認的為空格。 S.rjust(width,[fillchar]) #右對齊 S.splitlines([keepends]) #把S按照行分割符分為一個list,keepends是一個bool值,如果為真每行后而會保留行分割符。 S.swapcase() #大小寫互換?
三:列表 list
class list(object):"""list() -> new empty listlist(iterable) -> new list initialized from iterable's items"""def append(self, p_object): # real signature unknown; restored from __doc__""" L.append(object) -- append object to end """passdef count(self, value): # real signature unknown; restored from __doc__""" L.count(value) -> integer -- return number of occurrences of value """return 0def extend(self, iterable): # real signature unknown; restored from __doc__""" L.extend(iterable) -- extend list by appending elements from the iterable """passdef index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__"""L.index(value, [start, [stop]]) -> integer -- return first index of value.Raises ValueError if the value is not present."""return 0def insert(self, index, p_object): # real signature unknown; restored from __doc__""" L.insert(index, object) -- insert object before index """passdef pop(self, index=None): # real signature unknown; restored from __doc__"""L.pop([index]) -> item -- remove and return item at index (default last).Raises IndexError if list is empty or index is out of range."""passdef remove(self, value): # real signature unknown; restored from __doc__"""L.remove(value) -- remove first occurrence of value.Raises ValueError if the value is not present."""passdef reverse(self): # real signature unknown; restored from __doc__""" L.reverse() -- reverse *IN PLACE* """passdef sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__"""L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;cmp(x, y) -> -1, 0, 1"""passdef __add__(self, y): # real signature unknown; restored from __doc__""" x.__add__(y) <==> x+y """passdef __contains__(self, y): # real signature unknown; restored from __doc__""" x.__contains__(y) <==> y in x """passdef __delitem__(self, y): # real signature unknown; restored from __doc__""" x.__delitem__(y) <==> del x[y] """passdef __delslice__(self, i, j): # real signature unknown; restored from __doc__"""x.__delslice__(i, j) <==> del x[i:j]Use of negative indices is not supported."""passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __getslice__(self, i, j): # real signature unknown; restored from __doc__"""x.__getslice__(i, j) <==> x[i:j]Use of negative indices is not supported."""passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __iadd__(self, y): # real signature unknown; restored from __doc__""" x.__iadd__(y) <==> x+=y """passdef __imul__(self, y): # real signature unknown; restored from __doc__""" x.__imul__(y) <==> x*=y """passdef __init__(self, seq=()): # known special case of list.__init__"""list() -> new empty listlist(iterable) -> new list initialized from iterable's items# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <==> x<y """passdef __mul__(self, n): # real signature unknown; restored from __doc__""" x.__mul__(n) <==> x*n """pass@staticmethod # known case of __new__def __new__(S, *more): # real signature unknown; restored from __doc__""" T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __reversed__(self): # real signature unknown; restored from __doc__""" L.__reversed__() -- return a reverse iterator over the list """passdef __rmul__(self, n): # real signature unknown; restored from __doc__""" x.__rmul__(n) <==> n*x """passdef __setitem__(self, i, y): # real signature unknown; restored from __doc__""" x.__setitem__(i, y) <==> x[i]=y """passdef __setslice__(self, i, j, y): # real signature unknown; restored from __doc__"""x.__setslice__(i, j, y) <==> x[i:j]=yUse of negative indices is not supported."""passdef __sizeof__(self): # real signature unknown; restored from __doc__""" L.__sizeof__() -- size of L in memory, in bytes """pass__hash__ = Nonelist list?1:創建列表?
list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];?與字符串的索引一樣,列表索引從0開始。列表可以進行截取、組合等
2:訪問列表
list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print(list1[0]) print(list2[2:5])#截頭不截尾 ## physics ## [3, 4, 5]3:append方法:在列表末尾添加新的對象
aList = [123, 'xyz', 'zara', 'abc']; aList.append( 2009 ); print "Updated List : ", aList; ## Updated List : [123, 'xyz', 'zara', 'abc', 2009]4:count方法:統計某個元素在列表中出現的次數
aList = [123, 'xyz', 'zara', 123]; print(aList.count(123)) ## 25:extend() 函數用于在列表末尾一次性追加另一個序列中的多個值(用新列表擴展原來的列表)
aList = [123, 'xyz', 'zara', 'abc', 123]; bList = [2009, 'manni']; aList.extend(bList)print "Extended List : ", aList ; ## Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']6:index() 函數用于從列表中找出某個值第一個匹配項的索引位置
aList = [123, 'xyz', 'zara', 'abc'];print "Index for xyz : ", aList.index( 'xyz' ) ; print "Index for zara : ", aList.index( 'zara' ) ;##Index for xyz : 1 ## Index for zara : 27:insert() 函數用于將指定對象插入列表的指定位置
aList = [123, 'xyz', 'zara', 'abc']aList.insert( 3, 2009)print "Final List : ", aList## Final List : [123, 'xyz', 'zara', 2009, 'abc']insert()接收兩個參數,list.insert(index, obj),第一個參數index為要插入的索引位置,第二個參數要插入的元素
8:pop() 函數用于移除列表中的一個元素(默認最后一個元素),并且返回該元素的值
aList = [123, 'xyz', 'zara', 'abc'];print "A List : ", aList.pop(); print "B List : ", aList.pop();## A List : abc ## B List : zara9:remove() 函數用于移除列表中某個值的第一個匹配項
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];aList.remove('xyz'); print "List : ", aList; aList.remove('abc'); print "List : ", aList;## List : [123, 'zara', 'abc', 'xyz'] ## List : [123, 'zara', 'xyz']10:列表的四種遍歷方法
aList = [123, 'xyz', 'zara', 123];方法一:只遍歷列表中的值
for value in aList :print(value) #################### 123 xyz zara 123方法二:如果需要遍歷列表中的索引與值,就需要用到enumerate
for key,value in enumerate(aList) :print(key,value) ###################### (0, 123) (1, 'xyz') (2, 'zara') (3, 123)enumrate:為可迭代的對象添加序號,默認從0開始!因為列表的索引也是從0開始,所以我們在enumerate中不指定第二個參數,如有需要,可以指定從幾開始,如下:
for key,value in enumerate(aList,1) :print(key,value) ###################################### (1, 123) (2, 'xyz') (3, 'zara') (4, 123)方法三:
for i in range(len(aList)) :print(i,aList[i]) ############################## (0, 123) (1, 'xyz') (2, 'zara') (3, 123)range和xrange:指定范圍,生成指定的數字
方法四:使用iter()
for i in iter(aList) :print(i) ########################################## 123 xyz zara 123四:元組 tuple
lass tuple(object):"""tuple() -> empty tupletuple(iterable) -> tuple initialized from iterable's itemsIf the argument is a tuple, the return value is the same object."""def count(self, value): # real signature unknown; restored from __doc__""" T.count(value) -> integer -- return number of occurrences of value """return 0def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__"""T.index(value, [start, [stop]]) -> integer -- return first index of value.Raises ValueError if the value is not present."""return 0def __add__(self, y): # real signature unknown; restored from __doc__""" x.__add__(y) <==> x+y """passdef __contains__(self, y): # real signature unknown; restored from __doc__""" x.__contains__(y) <==> y in x """passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __getslice__(self, i, j): # real signature unknown; restored from __doc__"""x.__getslice__(i, j) <==> x[i:j]Use of negative indices is not supported."""passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __hash__(self): # real signature unknown; restored from __doc__""" x.__hash__() <==> hash(x) """passdef __init__(self, seq=()): # known special case of tuple.__init__"""tuple() -> empty tupletuple(iterable) -> tuple initialized from iterable's itemsIf the argument is a tuple, the return value is the same object.# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <==> x<y """passdef __mul__(self, n): # real signature unknown; restored from __doc__""" x.__mul__(n) <==> x*n """pass@staticmethod # known case of __new__def __new__(S, *more): # real signature unknown; restored from __doc__""" T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __rmul__(self, n): # real signature unknown; restored from __doc__""" x.__rmul__(n) <==> n*x """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" T.__sizeof__() -- size of T in memory, in bytes """passtuple tuple?Python的元組與列表類似,不同之處在于元組的元素不能修改。元組使用小括號,列表使用方括號。元組創建很簡單,只需要在括號中添加元素,并使用逗號隔開即可
tuple只有兩個可使用的功能:count , index
1:創建元組
tup1 = ();#創建空元組 tup1 = (50,);#元組中只包含一個元素時,需要在元素后面添加逗號元組與字符串類似,下標索引從0開始,可以進行截取,組合等。元組的訪問與列表一樣!
2:元組的連接組合
tup1 = (12, 34.56); tup2 = ('abc', 'xyz');# 以下修改元組元素操作是非法的。 # tup1[0] = 100;# 創建一個新的元組 tup3 = tup1 + tup2; print tup3; ########################################## (12, 34.56, 'abc', 'xyz')3:刪除元組
元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組,如下實例:
tup = ('physics', 'chemistry', 1997, 2000);print tup; del tup; print "After deleting tup : " print tup; ########################################## 以上實例元組被刪除后,輸出變量會有異常信息,輸出如下所示: ('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last):File "test.py", line 9, in <module>print tup; NameError: name 'tup' is not defined五:字典 dict
class dict(object):"""dict() -> new empty dictionarydict(mapping) -> new dictionary initialized from a mapping object's(key, value) pairsdict(iterable) -> new dictionary initialized as if via:d = {}for k, v in iterable:d[k] = vdict(**kwargs) -> new dictionary initialized with the name=value pairsin the keyword argument list. For example: dict(one=1, two=2)"""def clear(self): # real signature unknown; restored from __doc__""" 清除內容 """""" D.clear() -> None. Remove all items from D. """passdef copy(self): # real signature unknown; restored from __doc__""" 淺拷貝 """""" D.copy() -> a shallow copy of D """pass@staticmethod # known casedef fromkeys(S, v=None): # real signature unknown; restored from __doc__"""dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.v defaults to None."""passdef get(self, k, d=None): # real signature unknown; restored from __doc__""" 根據key獲取值,d是默認值 """""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """passdef has_key(self, k): # real signature unknown; restored from __doc__""" 是否有key """""" D.has_key(k) -> True if D has a key k, else False """return Falsedef items(self): # real signature unknown; restored from __doc__""" 所有項的列表形式 """""" D.items() -> list of D's (key, value) pairs, as 2-tuples """return []def iteritems(self): # real signature unknown; restored from __doc__""" 項可迭代 """""" D.iteritems() -> an iterator over the (key, value) items of D """passdef iterkeys(self): # real signature unknown; restored from __doc__""" key可迭代 """""" D.iterkeys() -> an iterator over the keys of D """passdef itervalues(self): # real signature unknown; restored from __doc__""" value可迭代 """""" D.itervalues() -> an iterator over the values of D """passdef keys(self): # real signature unknown; restored from __doc__""" 所有的key列表 """""" D.keys() -> list of D's keys """return []def pop(self, k, d=None): # real signature unknown; restored from __doc__""" 獲取并在字典中移除 """"""D.pop(k[,d]) -> v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised"""passdef popitem(self): # real signature unknown; restored from __doc__""" 獲取并在字典中移除 """"""D.popitem() -> (k, v), remove and return some (key, value) pair as a2-tuple; but raise KeyError if D is empty."""passdef setdefault(self, k, d=None): # real signature unknown; restored from __doc__""" 如果key不存在,則創建,如果存在,則返回已存在的值且不修改 """""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """passdef update(self, E=None, **F): # known special case of dict.update""" 更新{'name':'alex', 'age': 18000}[('name','sbsbsb'),]""""""D.update([E, ]**F) -> None. Update D from dict/iterable E and F.If E present and has a .keys() method, does: for k in E: D[k] = E[k]If E present and lacks .keys() method, does: for (k, v) in E: D[k] = vIn either case, this is followed by: for k in F: D[k] = F[k]"""passdef values(self): # real signature unknown; restored from __doc__""" 所有的值 """""" D.values() -> list of D's values """return []def viewitems(self): # real signature unknown; restored from __doc__""" 所有項,只是將內容保存至view對象中 """""" D.viewitems() -> a set-like object providing a view on D's items """passdef viewkeys(self): # real signature unknown; restored from __doc__""" D.viewkeys() -> a set-like object providing a view on D's keys """passdef viewvalues(self): # real signature unknown; restored from __doc__""" D.viewvalues() -> an object providing a view on D's values """passdef __cmp__(self, y): # real signature unknown; restored from __doc__""" x.__cmp__(y) <==> cmp(x,y) """passdef __contains__(self, k): # real signature unknown; restored from __doc__""" D.__contains__(k) -> True if D has a key k, else False """return Falsedef __delitem__(self, y): # real signature unknown; restored from __doc__""" x.__delitem__(y) <==> del x[y] """passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __init__(self, seq=None, **kwargs): # known special case of dict.__init__"""dict() -> new empty dictionarydict(mapping) -> new dictionary initialized from a mapping object's(key, value) pairsdict(iterable) -> new dictionary initialized as if via:d = {}for k, v in iterable:d[k] = vdict(**kwargs) -> new dictionary initialized with the name=value pairsin the keyword argument list. For example: dict(one=1, two=2)# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <==> x<y """pass@staticmethod # known case of __new__def __new__(S, *more): # real signature unknown; restored from __doc__""" T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __setitem__(self, i, y): # real signature unknown; restored from __doc__""" x.__setitem__(i, y) <==> x[i]=y """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" D.__sizeof__() -> size of D in memory, in bytes """pass__hash__ = Nonedict dict?字典是另一種可變容器模型,且可存儲任意類型對象。字典的每個鍵值(key=>value)對用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }鍵必須是唯一的,但值則不必。值可以取任何數據類型,但鍵必須是不可變的,如字符串,數字或元組。
1:訪問字典里的值
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};print "dict['Name']: ", dict['Name']; print "dict['Age']: ", dict['Age']; ########################################## dict['Name']: Zara dict['Age']: 72:修改字典里的值
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entryprint "dict['Age']: ", dict['Age']; print "dict['School']: ", dict['School']; ########################################## dict['Age']: 8 dict['School']: DPS School3:刪除操作
能刪單一的元素也能清空字典,清空只需一項操作。顯示刪除一個字典用del命令,如下實例:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};del dict['Name']; # 刪除鍵是'Name'的條目 dict.clear(); # 清空詞典所有條目 del dict ; # 刪除詞典print "dict['Age']: ", dict['Age']; print "dict['School']: ", dict['School']; ########################################## dict['Age']: Traceback (most recent call last):File "test.py", line 8, in <module>print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptableclear() 函數用于刪除字典內所有元素:
dict = {'Name': 'Zara', 'Age': 7};print "Start Len : %d" % len(dict) dict.clear() print "End Len : %d" % len(dict)注:clear函數是刪除字典里的所有元素,刪除后,該字典仍然存在,不過是個空字典而已
4:?copy() 函數返回一個字典的淺復制
dict1 = {'Name': 'Zara', 'Age': 7};dict2 = dict1.copy() print "New Dictinary : %s" % str(dict2) ########################################## New Dictinary : {'Age': 7, 'Name': 'Zara'}有關深淺復制的區別,請點擊這里!
5:fromkeys() 函數用于創建一個新字典,以序列seq中元素做字典的鍵,value為字典所有鍵對應的初始值
seq = ('name','age','sex') dic = dict.fromkeys(seq) print(dic) ######################################### {'age': None, 'name': None, 'sex': None}可以指定一個值,如:
seq = ('name','age','sex') dic = dict.fromkeys(seq,10) print(dic) ########################################## {'age': 10, 'name': 10, 'sex': 10}6:get() 函數返回指定鍵的值,如果值不在字典中返回默認值
dic = {'Name': 'Zara', 'Age': 27} print(dic.get('Age')) print(dic.get('Sex','Never'))#Never為設置的默認值 ########################################## 27 Never7:has_key() 函數用于判斷鍵是否存在于字典中,如果鍵在字典dict里返回true,否則返回false
dic = {'Name': 'Zara', 'Age': 27} print(dic.has_key('Name')) print(dic.has_key('Sex')) ########################################## True False8:items() 函數以列表返回可遍歷的(鍵, 值) 元組數組
dic = {'Name': 'Zara', 'Age': 27} print(dic.items()) ########################################## [('Age', 27), ('Name', 'Zara')]9:keys() 函數以列表返回一個字典所有的鍵
dic = {'Name': 'Zara', 'Age': 27} print(dic.keys()) ########################################## ['Age', 'Name']10:values() 函數以列表返回字典中的所有值
dic = {'Name': 'Zara', 'Age': 27} print(dic.values()) ########################################## [27, 'Zara']11:update() 函數把字典dict2的鍵/值對更新到dict1里
dict1 = {'Name': 'Zara', 'Age': 7} dict2 = {'Sex': 'female' } dict1.update(dict2) print(dict1) ########################################## {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}12:字典的遍歷
方法一:
dict1 = {'Age': 7, 'Name': 'Zara', 'Sex': 'female'} for k,v in dict1.items() :print(k,v) ########################################## ('Age', 7) ('Name', 'Zara') ('Sex', 'female')方法二:
dict1 = {'Age': 7, 'Name': 'Zara', 'Sex': 'female'} for (k,v) in dict1.items() :print(k,v) ########################################## ('Age', 7) ('Name', 'Zara') ('Sex', 'female')?
轉載于:https://www.cnblogs.com/ginvip/p/6243975.html
總結
以上是生活随笔為你收集整理的Python高手之路【二】python基本数据类型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: angularJS(5)
- 下一篇: Solr嵌套子文档的弊端以及一种替代方式