我們?cè)趯W(xué)習(xí)編程語言的時(shí)候,都會(huì)遇到數(shù)據(jù)類型,這種看著很基礎(chǔ)也不顯眼的東西,卻是很重要,本文介紹了python的數(shù)據(jù)類型,并就每種數(shù)據(jù)類型的方法作出了詳細(xì)的描述,可供知識(shí)回顧。
python2中 number = 123print (type(number)) number2 = 2147483647print (type(number2)) number2 = 2147483648 #我們會(huì)看到超過2147483647這個(gè)范圍,在py2中整形就會(huì)變成長整形了print (type(number2))#運(yùn)行結(jié)果<type 'int'> <type 'int'> <type 'long'>#python3中number = 123print (type(number)) number2 = 2147483648 print (type(number2)) #在python3中并不會(huì)#運(yùn)行結(jié)果<class 'int'> <class 'int'>
常用的method的如下:
.bit_length()
取最短bit位數(shù)
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 0
舉個(gè)例子:
number = 12 #1100 print(number.bit_length())#運(yùn)行結(jié)果4
浮點(diǎn)型可以看成就是小數(shù),type為float。
#浮點(diǎn)型number = 1.1print(type(number))#運(yùn)行結(jié)果<class 'float'>
常用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)"""pass
舉個(gè)例子
number = 0.25print(number.as_integer_ratio())#運(yùn)行結(jié)果(1, 4)
.hex()
以十六進(jìn)制表示浮點(diǎn)數(shù)
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 ""
舉個(gè)例子
number = 3.1415print(number.hex())#運(yùn)行結(jié)果0x1.921cac083126fp+1
.fromhex()
將十六進(jìn)制小數(shù)以字符串輸入,返回十進(jìn)制小數(shù)
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"""
舉個(gè)例子
print(float.fromhex('0x1.921cac083126fp+1'))#運(yùn)行結(jié)果3.1415
.is_integer()
判斷小數(shù)是不是整數(shù),比如3.0為一個(gè)整數(shù),而3.1不是,返回布爾值
def is_integer(self, *args, **kwargs): # real signature unknown""" Return True if the float is an integer. """pass
舉個(gè)例子
number = 3.1415number2 = 3.0print(number.is_integer())print(number2.is_integer())#運(yùn)行結(jié)果False True
字符串就是一些列的字符,在Python中用單引號(hào)或者雙引號(hào)括起來,多行可以用三引號(hào)。
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)#運(yùn)行結(jié)果my name is Frank my name is Frank my name is Frank I'm 23 years old
常用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 ""
舉個(gè)例子
name = 'my name is Frank'#運(yùn)行結(jié)果My name is frank
.center()
字符居中,指定寬度和填充字符(默認(rèn)為空格)
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 ""
舉個(gè)例子
flag = "Welcome Frank"print(flag.center(50,'*'))#運(yùn)行結(jié)果******************Welcome Frank*******************
.count()
計(jì)算字符串中某個(gè)字符的個(gè)數(shù),可以指定索引范圍
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 0
舉個(gè)例子
flag = 'aaababbcccaddadaddd'print(flag.count('a'))print(flag.count('a',0,3))#運(yùn)行結(jié)果7 3
.encode()
編碼,在python3中,str默認(rèn)是unicode數(shù)據(jù)類型,可以將其編碼成bytes數(shù)據(jù)
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""
舉個(gè)例子
flag = 'aaababbcccaddadaddd'print(flag.encode('utf8'))#運(yùn)行結(jié)果b'aaababbcccaddadaddd'
.endswith()
判斷字符串結(jié)尾是否是某個(gè)字符串和字符,可以通過索引指定范圍
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 False
舉個(gè)例子
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))#運(yùn)行結(jié)果False True False True False
.expandtabs()
把制表符tab(" ")轉(zhuǎn)換為空格
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 ""
舉個(gè)例子
flag = " hello python!"print(flag)print(flag.expandtabs()) #默認(rèn)tabsize=8print(flag.expandtabs(20))#運(yùn)行結(jié)果hello python! #一個(gè)tab,長度為4個(gè)空格hello python! #8個(gè)空格hello python! #20個(gè)空格
.find()
查找字符,返回索引值,可以通過指定索引范圍內(nèi)查找,查找不到返回-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 0
舉個(gè)例子
flag = "hello python!"print(flag.find('e'))print(flag.find('a'))print(flag.find('h',4,-1))#運(yùn)行結(jié)果1 -1 9
.format()
格式化輸出,使用"{}"符號(hào)作為操作符。
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 '}')."""pass
舉個(gè)例子
#位置參數(shù)flag = "hello {0} and {1}!"print(flag.format('python','php')) flag = "hello {} and {}!"print(flag.format('python','php'))#變量參數(shù)flag = "{name} is {age} years old!"print(flag.format(name='Frank',age = 23))#結(jié)合列表infor=["Frank",23]print("{0[0]} is {0[1]} years old".format(infor))#運(yùn)行結(jié)果hello python and php! hello python and php! Frank is 23 years old! Frank is 23 years old
.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 ""
舉個(gè)例子
people={'name':['Frank','Caroline'],'age':['23','22'], }print("My name is {name[0]},i am {age[1]} years old !".format_map(people))#運(yùn)行結(jié)果My name is Frank,i am 22 years old !
.index()
根據(jù)字符查找索引值,可以指定索引范圍查找,查找不到會(huì)報(bào)錯(cuò)
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 0
舉個(gè)例子
flag = "hello python!"print(flag.index("e"))print(flag.index("o",6,-1))#運(yùn)行結(jié)果1 10
.isalnum()
判斷是否是字母或數(shù)字組合,返回布爾值
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 False
舉個(gè)例子
flag = "hellopython"flag1 = "hellopython22"flag2 = "hellopython!!"flag3 = "!@#!#@!!@"print(flag.isalnum())print(flag1.isalnum())print(flag2.isalnum())print(flag3.isalnum())#運(yùn)行結(jié)果True True False False
.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 False
舉個(gè)例子
flag = "hellopython"flag1 = "hellopython22"print(flag.isalpha())print(flag1.isalpha())#運(yùn)行結(jié)果True False
.isdecimal()
判斷是否是一個(gè)十進(jìn)制正整數(shù),返回布爾值
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 False
舉個(gè)例子
number = "1.2"number1 = "12"number2 = "-12"number3 = "1222"print(number.isdecimal())print(number1.isdecimal())print(number2.isdecimal())print(number3.isdecimal())#運(yùn)行結(jié)果False True False True
isdigit()
判斷是否是一個(gè)正整數(shù),返回布爾值,與上面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 False
舉個(gè)例子
number = "1.2"number1 = "12"number2 = "-12"number3 = "11"print(number.isdigit())print(number1.isdigit())print(number2.isdigit())print(number3.isdigit())#運(yùn)行結(jié)果False True False True
.isidentifier()
判斷是否為python中的標(biāo)識(shí)符
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 False
舉個(gè)例子
flag = "cisco"flag1 = "1cisco"flag2 = "print"print(flag.isidentifier())print(flag1.isidentifier())print(flag2.isidentifier())#運(yùn)行結(jié)果True False True
.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 False
舉個(gè)例子
flag = "cisco"flag1 = "cisco222"flag2 = "Cisco"print(flag.islower())print(flag1.islower())print(flag2.islower())#運(yùn)行結(jié)果True True False
.isnumeric()
判斷是否為數(shù)字,這個(gè)很強(qiáng)大,中文字符,繁體字?jǐn)?shù)字都可以識(shí)別
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 False
舉個(gè)例子
number = "123"number1 = "一"number2 = "壹"number3 = "123q"number4 = "1.1"print(number.isnumeric())print(number1.isnumeric())print(number2.isnumeric())print(number3.isnumeric())print(number4.isnumeric())#運(yùn)行結(jié)果True True True False False
.isprintable()
判斷引號(hào)里面的是否都是可打印的,返回布爾值
def isprintable(self): # real signature unknown; restored from __doc__"""S.isprintable() -> bool Return True if all characters in S are considered printable in repr() or S is empty, False otherwise."""return False
舉個(gè)例子
flag = " 123"flag1 = " "flag2 = "123"flag3 = r" 123" # r 可以是轉(zhuǎn)義字符失效print(flag.isprintable()) # 不可打印print(flag1.isprintable()) # 不可打印print(flag2.isprintable())print(flag3.isprintable())#運(yùn)行結(jié)果False False True True
.isspace()
判斷字符串里面都是空白位,空格或者tab,返回布爾值
def isspace(self): # real signature unknown; restored from __doc__"""S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise."""return False
舉個(gè)例子
flag = ' ' #4個(gè)空格flag1 = ' '#2個(gè)tabprint(flag.isspace())print(flag1.isspace())#運(yùn)行結(jié)果True True
.istitle()
判斷字符串里面的字符是否都是大寫開頭,返回布爾值
def isspace(self): # real signature unknown; restored from __doc__"""S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise."""return False
舉個(gè)例子
flag = "Welcome Frank"flag1 = "Welcome frank"print(flag.istitle())print(flag1.istitle())#運(yùn)行結(jié)果True False
.isupper()
判斷是否都是字符串里的字母都是大寫
def isupper(self): # real signature unknown; restored from __doc__"""S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise."""return False
舉個(gè)例子
flag = "WELCOME1"flag1 = "Welcome1"print(flag.isupper())print(flag1.isupper())#運(yùn)行結(jié)果True False
.join()
將字符串以指定的字符連接生成一個(gè)新的字符串
def join(self, iterable): # real signature unknown; restored from __doc__"""S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S."""return ""
舉個(gè)例子
flag = "welcome"print("#".join(flag))#運(yùn)行結(jié)果w#e#l#c#o#m#e
.ljust()
左對(duì)齊,可指定字符寬度和填充字符
def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space)."""return ""
舉個(gè)例子
flag = "welcome"print(flag.ljust(20,"*"))#運(yùn)行結(jié)果welcome*************
.rjust()
右對(duì)齊,可指定字符寬度和填充字符
def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space)."""return ""
舉個(gè)例子
flag = "welcome"print(flag.rjust(20,"*"))#運(yùn)行結(jié)果*************welcome
.lower()
對(duì)字符串里的所有字母轉(zhuǎn)小寫
def lower(self): # real signature unknown; restored from __doc__"""S.lower() -> str Return a copy of the string S converted to lowercase."""return ""
舉個(gè)例子
flag = "WELcome"#運(yùn)行結(jié)果welcome
.upper()
對(duì)字符串里的所有字母轉(zhuǎn)大寫
def upper(self): # real signature unknown; restored from __doc__"""S.upper() -> str Return a copy of S converted to uppercase."""return ""
舉個(gè)例子
flag = "WELcome"print(flag.upper())#運(yùn)行結(jié)果WELCOME
.title()
對(duì)字符串里的單詞進(jìn)行首字母大寫轉(zhuǎn)換
def title(self): # real signature unknown; restored from __doc__"""S.title() -> str Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case."""return ""
舉個(gè)例子
flag = "welcome frank"print(flag.title())#運(yùn)行結(jié)果Welcome Frank
.lstrip()
默認(rèn)去除左邊空白字符,可指定去除的字符,去除指定的字符后,會(huì)被空白占位。
def lstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead."""return ""
舉個(gè)例子
flag = " welcome frank"flag1 = "@@@@welcome frank"print(flag.lstrip())print(flag.lstrip("@"))print(flag.lstrip("@").lstrip())#運(yùn)行結(jié)果welcome frank welcome frank welcome frank
.rstrip()
默認(rèn)去除右邊空白字符,可指定去除的字符,去除指定的字符后,會(huì)被空白占位。
def rstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead."""return ""
舉個(gè)例子
flag = "welcome frank "flag1 = "welcome frank@@@@"# print(flag.title())print(flag.rstrip())print(flag.rstrip("@"))print(flag.rstrip("@").rstrip())#運(yùn)行結(jié)果welcome frank welcome frank #右邊有4個(gè)空格welcome frank
.strip()
默認(rèn)去除兩邊空白字符,可指定去除的字符,去除指定的字符后,會(huì)被空白占位。
def strip(self, chars=None): # real signature unknown; restored from __doc__"""S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead."""return ""
舉個(gè)例子
flag = " welcome frank "flag1 = "@@@@welcome frank@@@@"# print(flag.title())print(flag.strip())print(flag.strip("@"))print(flag.strip("@").strip())#運(yùn)行結(jié)果welcome frank welcome frank #右邊有4個(gè)空格welcome frank
.maketrans()和translate()
創(chuàng)建字符映射的轉(zhuǎn)換表,對(duì)于接受兩個(gè)參數(shù)的最簡(jiǎn)單的調(diào)用方式,第一個(gè)參數(shù)是字符串,表示需要轉(zhuǎn)換的字符,第二個(gè)參數(shù)也是字符串表示轉(zhuǎn)換的目標(biāo)。兩個(gè)字符串的長度必須相同,為一一對(duì)應(yīng)的關(guān)系。
def maketrans(self, *args, **kwargs): # real signature unknown"""Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result."""pass
def translate(self, table): # real signature unknown; restored from __doc__"""S.translate(table) -> str Return a copy of the string S in which each character has been mapped through the given translation table. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted."""return ""
舉個(gè)例子
intab = "aeiou"outtab = "12345"trantab = str.maketrans(intab, outtab) str = "this is string example....wow!!!"print (str.translate(trantab))#運(yùn)行結(jié)果th3s 3s str3ng 2x1mpl2....w4w!!!
.partition()
以指定字符分割,返回一個(gè)元組
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com