Python數據類型及其方法詳解 我們在學習編程語言的時候,都會遇到數據類型,這種看著很基礎也不顯眼的東西,卻是很重要,本文介紹了python的數據類型,並就每種數據類型的方法作出了詳細的描述,可供知識回顧。 一、整型和長整型 整型:數據是不包含小數部分的數值型數據,比如我們所說的1、2、3、4、1 ...
Python數據類型及其方法詳解
我們在學習編程語言的時候,都會遇到數據類型,這種看著很基礎也不顯眼的東西,卻是很重要,本文介紹了python的數據類型,並就每種數據類型的方法作出了詳細的描述,可供知識回顧。
一、整型和長整型
整型:數據是不包含小數部分的數值型數據,比如我們所說的1、2、3、4、122,其type為"int" 長整型:也是一種數字型數據,但是一般數字很大,其type為"long" 在python2中區分整型和長整型,在32位的機器上,取值範圍是-2147483648~2147483647,超出範圍的為長整型,在64位的機器上,取值範圍為-9223372036854775808~9223372036854775807(通常也與python的解釋器的位數有關)。 在python3中,不存在整型和長整型之分,只有整型。 舉個例子:python2中 number = 123 print (type(number)) number2 = 2147483647 print (type(number2)) number2 = 2147483648 #我們會看到超過2147483647這個範圍,在py2中整形就會變成長整形了 print (type(number2)) #運行結果 <type 'int'> <type 'int'> <type 'long'> #python3中 number = 123 print (type(number)) number2 = 2147483648 print (type(number2)) #在python3中並不會 #運行結果 <class 'int'> <class 'int'>View Code
常用的method的如下:
.bit_length()
取最短bit位數
def bit_length(self): # real signature unknown; restored from __doc__ """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() 6 """ return 0View Code
舉個例子:
number = 12 #1100 print(number.bit_length()) #運行結果 4View Code
二、浮點型
浮點型可以看成就是小數,type為float。
#浮點型 number = 1.1 print(type(number)) #運行結果 <class 'float'>View Code
常用method的如下:
.as_integer_ratio()
返回元組(X,Y),number = k ,number.as_integer_ratio() ==>(x,y) x/y=k
def as_integer_ratio(self): # real signature unknown; restored from __doc__ """ float.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original float and with a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs. >>> (10.0).as_integer_ratio() (10, 1) >>> (0.0).as_integer_ratio() (0, 1) >>> (-.25).as_integer_ratio() (-1, 4) """ passView Code
舉個例子
number = 0.25 print(number.as_integer_ratio()) #運行結果 (1, 4)View Code
.hex()
以十六進位表示浮點數
def hex(self): # real signature unknown; restored from __doc__ """ float.hex() -> string Return a hexadecimal representation of a floating-point number. >>> (-0.1).hex() '-0x1.999999999999ap-4' >>> 3.14159.hex() '0x1.921f9f01b866ep+1' """ return ""View Code
舉個例子
number = 3.1415 print(number.hex()) #運行結果 0x1.921cac083126fp+1View Code
.fromhex()
將十六進位小數以字元串輸入,返回十進位小數
def fromhex(string): # real signature unknown; restored from __doc__ """ float.fromhex(string) -> float Create a floating-point number from a hexadecimal string. >>> float.fromhex('0x1.ffffp10') 2047.984375 >>> float.fromhex('-0x1p-1074') -5e-324 """View Code
舉個例子
print(float.fromhex('0x1.921cac083126fp+1')) #運行結果 3.1415View Code
.is_integer()
判斷小數是不是整數,比如3.0為一個整數,而3.1不是,返回布爾值
def is_integer(self, *args, **kwargs): # real signature unknown """ Return True if the float is an integer. """ passView Code
舉個例子
number = 3.1415 number2 = 3.0 print(number.is_integer()) print(number2.is_integer()) #運行結果 False TrueView Code
三、字元類型
字元串就是一些列的字元,在Python中用單引號或者雙引號括起來,多行可以用三引號。
name = 'my name is Frank' name1 = "my name is Frank" name2 = '''my name is Frank I'm 23 years old, ''' print(name) print(name1) print(name2) #運行結果 my name is Frank my name is Frank my name is Frank I'm 23 years oldView Code
常用method的如下:
.capitalize()
字元串首字元大寫
def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return ""View Code
舉個例子
name = 'my name is Frank' #運行結果 My name is frankView Code
.center()
字元居中,指定寬度和填充字元(預設為空格)
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return ""View Code
舉個例子
flag = "Welcome Frank" print(flag.center(50,'*')) #運行結果 ******************Welcome Frank*******************View Code
.count()
計算字元串中某個字元的個數,可以指定索引範圍
def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0View Code
舉個例子
flag = 'aaababbcccaddadaddd' print(flag.count('a')) print(flag.count('a',0,3)) #運行結果 7 3View Code
.encode()
編碼,在python3中,str預設是unicode數據類型,可以將其編碼成bytes數據
def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ """ S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return b""View Code
舉個例子
flag = 'aaababbcccaddadaddd' print(flag.encode('utf8')) #運行結果 b'aaababbcccaddadaddd'View Code
.endswith()
判斷字元串結尾是否是某個字元串和字元,可以通過索引指定範圍
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return 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 FalseView Code
舉個例子
flag = 'aaababbcccaddadaddd' print(flag.endswith('aa')) print(flag.endswith('ddd')) print(flag.endswith('dddd')) print(flag.endswith('aaa',0,3)) print(flag.endswith('aaa',0,2)) #運行結果 False True False True FalseView Code
.expandtabs()
把製表符tab("\t")轉換為空格
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ """ S.expandtabs(tabsize=8) -> str Return 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 ""View Code
舉個例子
flag = "\thello python!" print(flag) print(flag.expandtabs()) #預設tabsize=8 print(flag.expandtabs(20)) #運行結果 hello python! #一個tab,長度為4個空格 hello python! #8個空格 hello python! #20個空格View Code
.find()
查找字元,返回索引值,可以通過指定索引範圍內查找,查找不到返回-1
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0View Code
舉個例子
flag = "hello python!" print(flag.find('e')) print(flag.find('a')) print(flag.find('h',4,-1)) #運行結果 1 -1 9View Code
.format()
格式化輸出,使用"{}"符號作為操作符。
def format(self, *args, **kwargs): # known special case of str.format """ S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ passView Code
舉個例子
#位置參數 flag = "hello {0} and {1}!" print(flag.format('python','php')) flag = "hello {} and {}!" print(flag.format('python','php')) #變數參數 flag = "{name} is {age} years old!" print(flag.format(name='Frank',age = 23)) #結合列表 infor=["Frank",23] print("{0[0]} is {0[1]} years old".format(infor)) #運行結果 hello python and php! hello python and php! Frank is 23 years old! Frank is 23 years oldView Code
.format_map()
格式化輸出
def format_map(self, mapping): # real signature unknown; restored from __doc__ """ S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}'). """ return ""View Code
舉個例子
people={ 'name':['Frank','Caroline'], 'age':['23','22'], } print("My name is {name[0]},i am {age[1]} years old !".format_map(people)) #運行結果 My name is Frank,i am 22 years old !View Code
.index()
根據字元查找索引值,可以指定索引範圍查找,查找不到會報錯
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0View Code
舉個例子
flag = "hello python!" print(flag.index("e")) print(flag.index("o",6,-1)) #運行結果 1 10View Code
.isalnum()
判斷是否是字母或數字組合,返回布爾值
def isalnum(self): # real signature unknown; restored from __doc__ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return FalseView Code
舉個例子
flag = "hellopython" flag1 = "hellopython22" flag2 = "hellopython!!" flag3 = "!@#!#@!!@" print(flag.isalnum()) print(flag1.isalnum()) print(flag2.isalnum()) print(flag3.isalnum()) #運行結果 True True False FalseView Code
.isalpha()
判斷是否是字母組合,返回布爾值
def isalpha(self): # real signature unknown; restored from __doc__ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return FalseView Code
舉個例子
flag = "hellopython" flag1 = "hellopython22" print(flag.isalpha()) print(flag1.isalpha()) #運行結果 True FalseView Code
.isdecimal()
判斷是否是一個十進位正整數,返回布爾值
def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return FalseView Code
舉個例子
number = "1.2" number1 = "12" number2 = "-12" number3 = "1222" print(number.isdecimal()) print(number1.isdecimal()) print(number2.isdecimal()) print(number3.isdecimal()) #運行結果 False True False TrueView Code
isdigit()
判斷是否是一個正整數,返回布爾值,與上面isdecimal類似
def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return FalseView Code
舉個例子
number = "1.2" number1 = "12" number2 = "-12" number3 = "11" print(number.isdigit()) print(number1.isdigit()) print(number2.isdigit()) print(number3.isdigit()) #運行結果 False True False TrueView Code
.isidentifier()
判斷是否為python中的標識符
def isidentifier(self): # real signature unknown; restored from __doc__ """ S.isidentifier() -> bool Return True if S is a valid identifier according to the language definition. Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". """ return FalseView Code
舉個例子
flag = "cisco" flag1 = "1cisco" flag2 = "print" print(flag.isidentifier()) print(flag1.isidentifier()) print(flag2.isidentifier()) #運行結果 True False TrueView Code
.islower()
判斷字元串中的字母是不是都是小寫,返回布爾值
def islower(self): # real signature unknown; restored from __doc__ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return FalseView Code
舉個例子
flag = "cisco" flag1 = "cisco222" flag2 = "Cisco" print(flag.islower()) print(flag1.islower()) print(flag2.islower()) #運行結果 True True FalseView Code
.isnumeric()
判斷是否為數字,這個很強大,中文字元,繁體字數字都可以識別
def isnumeric(self): # real signature unknown; restored from __doc__ """ S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise. """ return FalseView Code
舉個例子
number = "123" number1 = "一" number2 = "壹" number3 = "123q" number4 = "1.1" print(number.isnumeric()) print(number1.isnumeric()) print