我们在学习编程语言的时候,都会遇到数据类型,这种看着很基础也不显眼的东西,却是很重要,本文介绍了python的数据类型,并就每种数据类型的方法作出了详细的描述,可供知识回顾。
python2中 number = 123print (type(number)) number2 = 2147483647print (type(number2)) number2 = 2147483648 #我们会看到超过2147483647这个范围,在py2中整形就会变成长整形了print (type(number2))#运行结果<type 'int'> <type 'int'> <type 'long'>#python3中number = 123print (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.1print(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.25print(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.1415print(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.1415number2 = 3.0print(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(" ")转换为空格
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 = " hello python!"print(flag)print(flag.expandtabs()) #默认tabsize=8print(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(number2.isnumeric())print(number3.isnumeric())print(number4.isnumeric())#运行结果True True True False FalseView Code
.isprintable()
判断引号里面的是否都是可打印的,返回布尔值
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 FalseView Code
举个例子
flag = " 123"flag1 = " "flag2 = "123"flag3 = r" 123" # r 可以是转义字符失效print(flag.isprintable()) # 不可打印print(flag1.isprintable()) # 不可打印print(flag2.isprintable())print(flag3.isprintable())#运行结果False False True TrueView Code
.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 FalseView Code
举个例子
flag = ' ' #4个空格flag1 = ' '#2个tabprint(flag.isspace())print(flag1.isspace())#运行结果True TrueView Code
.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 FalseView Code
举个例子
flag = "Welcome Frank"flag1 = "Welcome frank"print(flag.istitle())print(flag1.istitle())#运行结果True FalseView Code
.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 FalseView Code
举个例子
flag = "WELCOME1"flag1 = "Welcome1"print(flag.isupper())print(flag1.isupper())#运行结果True FalseView Code
.join()
将字符串以指定的字符连接生成一个新的字符串
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 ""View Code
举个例子
flag = "welcome"print("#".join(flag))#运行结果w#e#l#c#o#m#eView Code
.ljust()
左对齐,可指定字符宽度和填充字符
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 ""View Code
举个例子
flag = "welcome"print(flag.ljust(20,"*"))#运行结果welcome*************View Code
.rjust()
右对齐,可指定字符宽度和填充字符
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 ""View Code
举个例子
flag = "welcome"print(flag.rjust(20,"*"))#运行结果*************welcomeView Code
.lower()
对字符串里的所有字母转小写
def lower(self): # real signature unknown; restored from __doc__"""S.lower() -> str Return a copy of the string S converted to lowercase."""return ""View Code
举个例子
flag = "WELcome"#运行结果welcomeView Code
.upper()
对字符串里的所有字母转大写
def upper(self): # real signature unknown; restored from __doc__"""S.upper() -> str Return a copy of S converted to uppercase."""return ""View Code
举个例子
flag = "WELcome"print(flag.upper())#运行结果WELCOMEView Code
.title()
对字符串里的单词进行首字母大写转换
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 ""View Code
举个例子
flag = "welcome frank"print(flag.title())#运行结果Welcome FrankView Code
.lstrip()
默认去除左边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。
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 ""View Code
举个例子
flag = " welcome frank"flag1 = "@@@@welcome frank"print(flag.lstrip())print(flag.lstrip("@"))print(flag.lstrip("@").lstrip())#运行结果welcome frank welcome frank welcome frankView Code
.rstrip()
默认去除右边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。
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 ""View Code
举个例子
flag = "welcome frank "flag1 = "welcome frank@@@@"# print(flag.title())print(flag.rstrip())print(flag.rstrip("@"))print(flag.rstrip("@").rstrip())#运行结果welcome frank welcome frank #右边有4个空格welcome frankView Code
.strip()
默认去除两边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。
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 ""View Code
举个例子
flag = " welcome frank "flag1 = "@@@@welcome frank@@@@"# print(flag.title())print(flag.strip())print(flag.strip("@"))print(flag.strip("@").strip())#运行结果welcome frank welcome frank #右边有4个空格welcome frankView Code
.maketrans()和translate()
创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。
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."""passView Code
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 ""View Code
举个例子
intab = "aeiou"outtab = "12345"trantab = str.maketrans(intab, outtab) str = "this is string example....wow!!!"print (str.translate(trantab))#运行结果th3s 3s str3ng 2x1mpl2....w4w!!!View Code
.partition()
以指定字符分割,返回一个元组