Python基本数据类型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基本数据类型相关的知识,希望对你有一定的参考价值。
目录:
1、运算符
2、type()、dir()、help()函数
3、基本数据类型常用功能之int、str操作.
正文:
一、运算符
二、type()、dir()、help()函数
1、type()函数用来判断数据类型
>>> type(123) <class ‘int‘> >>> type(123.0) <class ‘float‘> >>> type("123") <class ‘str‘> >>> >>> a = "yangbin" >>> type(a) is int False >>> type(a) is str True >>>
注: 还有一种判断数据类型的方法:isinstance()函数.
>>> a ‘yangbin‘ >>> isinstance(a, str) True >>> isinstance(a, int) False >>>
对于type()和isinstance()两者的区别,就是对于subclass之类的类型判断时type就不行了,必须用isinstance来判断。此处用type()即可,之后会再次提到。
2、dir()函数用来查看对像内所有属性及方法。
python内置方法有很多,无论是初学还是经通python的程序员都不能全部记住所有方法,这时候dir()函数就非常有用了。在python中任何东西都是对像,一种数据类型,一个模块等,都有自己的属性和方法,除了常用方法外,其它的不需要全部记住,交给dir()函数就好了。
>>> dir(int) [‘__abs__‘, ‘__add__‘, ‘__and__‘, ‘__bool__‘, ‘__ceil__‘, ‘__class__‘, ‘__delattr__‘, ‘__dir__‘, ‘__divmod__‘, ‘__doc__‘, ‘__eq__‘, ‘__float__‘, ‘__floor__‘, ‘__floordiv__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__index__‘, ‘__init__‘, ‘__int__‘, ‘__invert__‘, ‘__le__‘, ‘__lshift__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__neg__‘, ‘__new__‘, ‘__or__‘, ‘__pos__‘, ‘__pow__‘, ‘__radd__‘, ‘__rand__‘, ‘__rdivmod__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rfloordiv__‘, ‘__rlshift__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__ror__‘, ‘__round__‘, ‘__rpow__‘, ‘__rrshift__‘, ‘__rshift__‘, ‘__rsub__‘, ‘__rtruediv__‘, ‘__rxor__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__sub__‘, ‘__subclasshook__‘, ‘__truediv__‘, ‘__trunc__‘, ‘__xor__‘, ‘bit_length‘, ‘conjugate‘, ‘denominator‘, ‘from_bytes‘, ‘imag‘, ‘numerator‘, ‘real‘, ‘to_bytes‘] >>>
>>> import sys # 导入一个Python模块. >>> dir() # 查看该模块的属性和方法. [‘__builtins__‘, ‘__doc__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘a‘, ‘sys‘] >>>
3、help()函数用来查看对象的属性和属性介绍。
>>> help(int) Help on class int in module builtins: class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal 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 to interpret the base from the string as an integer literal. | >>> int(‘0b100‘, base=0) | 4 | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | self != 0 | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) ...
总的来说,help()函数的查询结果更全面,包括了dir()的查询结果。
三、基本数据类型常用功能之int、str操作.
1、int类型的常用功能:
查看都有哪些功能:
>>> dir(int) ...
查看各功能的用法:
>>> help(int) ...
a. bit_length
功能: 返回表示该数字的时占用的最少位数
>>> help(int.bit_length) Help on method_descriptor: bit_length(...) int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) ‘0b100101‘ >>> (37).bit_length() 6
例:
>>> a = 21 >>> bin(a) ‘0b10101‘ >>> a.bit_length() 5 >>>
b. __abs__
功能: 取绝对值。
>>> help(int.__abs__) Help on wrapper_descriptor: __abs__(self, /) abs(self)
例:
>>> a = -2 >>> abs(a) 2 >>> a.__abs__() 2 >>>
c. __add__
功能: 相加求和
>>> help(int.__add__) Help on wrapper_descriptor: __add__(self, value, /) Return self+value.
例:
>>> num = 100 >>> num.__add__(10) 110 >>>
d. __and__
功能: 位运算
>>> help(int.__and__) Help on wrapper_descriptor: __and__(self, value, /) Return self&value.
例:
>>> a = 12 >>> b = 11 >>> a.__and__(b) 8 >>> >>> a 12 >>> b 11 >>> a & b 8 >>>
解释:
变量a和变量b的二进制格式如下:
a=1100
b=1011
a和b相与,得到的结果为1000,换算成十进制为8.
注: 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0.
2、str类型的常用功能:
查看都有哪些功能:
>>> dir(str) ...
查看各功能的用法:
>>> help(str) ...
a. __add__
功能: 把两字符串组合在一起。
>>> help(str.__add__) Help on wrapper_descriptor: __add__(self, value, /) Return self+value.
例:
>>> a = "learn" >>> b = "python" >>> a.__add__(b) ‘learnpython‘ >>> b = " python" >>> a.__add__(b) ‘learn python‘ >>>
b. __contains__
功能: 判断key是否在self中,返回True或False.
>>> help(str.__contains__) Help on wrapper_descriptor: __contains__(self, key, /) Return key in self.
例如:
>>> a = "python" >>> b = "I like python" >>> b.__contains__(a) # b表示self, a表示key. True >>> >>> a ‘python‘ >>> b ‘I like python‘ >>> a in b True >>>
c. __len__
功能: 返回字符串的长度.
>>> help(str.__len__) Help on wrapper_descriptor: __len__(self, /) Return len(self).
例:
>>> num = "python" >>> num.__len__() 6 >>> len(num) 6 >>>
d. __lt__
功能: 返回self小于value的值,成立则返回True,否则返回False.
>>> help(str.__lt__) Help on wrapper_descriptor: __lt__(self, value, /) Return self<value.
例:
>>> a = "Python" >>> b = "pythonn" >>> a.__lt__(b) True >>> >>> a < b True >>>
e. isalnum
功能: 判断变量里面包含字母或数字,就返回True,否则返回False.
>>> help(str.isalnum) Help on method_descriptor: isalnum(...) S.isalnum() -> bool Return True if all characters(字符) in S are alphanumeric(数字字母) and there is at least one character in S, False otherwise.
例:
>>> a = "python" >>> a.isalnum() True >>> a = "python123" >>> a.isalnum() True >>>
f. isalpha
功能: 判断变量里面包含字母,就返回True,否则返回False.
>>> help(str.isalpha) Help on method_descriptor: isalpha(...) S.isalpha() -> bool Return True if all characters in S are alphabetic(字母) and there is at least one character in S, False otherwise.
例:
>>> a ‘python123‘ >>> a.isalpha() False # 变量a中有数字,返回False. >>> b = "python" >>> b.isalpha() True >>>
g. isdigit
功能: 判断变量里面包含数字,就返回True,否则返回False.
>>> help(str.isdigit) Help on method_descriptor: isdigit(...) S.isdigit() -> bool Return True if all characters in S are digits(数字) and there is at least one character in S, False otherwise.
例:
>>> a ‘python123‘ >>> a.isdigit() False # 变量a中包含字母,返回“False”. >>> b = 123 >>> b.isdigit # 变量b是int类型,不被允许. Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: ‘int‘ object has no attribute ‘isdigit‘ >>> c = "123" # 变量c中的数字时str类型,返回True. >>> c.isdigit() True >>>
h. count
功能: 用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
>>> help(str.count) Help on method_descriptor: count(...) 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.
例:
>>> a = "Pythonth" >>> a.count("th") 2 >>> >>> a.count("th",1,4) 1 >>>
i. endswith
功能: 用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。从start开始,不包括end.
>>> help(str.endswith) Help on method_descriptor: endswith(...) 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.
例:
>>> a = "I like Python" >>> a.endswith("thon") True >>> a.endswith("ke",0,6) True >>> a.endswith("ke",0,5) False >>>
j. encode
功能: 用encoding指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。
>>> help(str.encode) Help on method_descriptor: encode(...) 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.
Python2版本中,字符串默认是unicode编码;
Python3版本中, 字符串默认是utf-8编码;
encode的作用是将unicode/utf-8编码转换成encoding指定的编码格式的字符串。
例:
拿Python3版本来说,字符串默认是utf-8编码;
>>> name = "中国" >>> a = name.encode("gbk") # 此处字符串编码由utf-8转换为gbk编码. >>> a b‘\xd6\xd0\xb9\xfa‘ >>> b = a.decode("gbk") # 使用decode()函数解码"gbk"为系统默认的"utf-8". >>> b ‘中国‘ >>>
k. center
功能: 返回一个原字符串居中,并使用空格填充至长度width的新字符串。默认填充字符为空格。
>>> help(str.center) Help on method_descriptor: center(...) 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)
例:
>>> name = "python" >>> name.center(15, "a") ‘aaaaapythonaaaa‘ >>>
l. find
功能: 用于检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串则返回开始的索引值,否则返回-1。
>>> help(str.find) Help on method_descriptor: find(...) 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.
例:
>>> name = "python " >>> name ‘python ‘ >>> name.find("y") 1 >>> name.find("on") 4 >>> name.find("py") 0 >>> name.find("y",1) 1 >>> name.find("y",3,5) -1
m. rfind
功能: 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
>>> help(str.rfind) Help on method_descriptor: rfind(...) S.rfind(sub[, start[, end]]) -> int Return the highest 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.
例:
>>> name = "python and python" >>> name.rfind("py") 11 >>> name.rfind("py",0, 10) 0 >>> name.rfind("py",10, 0) -1 >>> name.rfind("py",10, 15) 11 >>>
n. index
功能: 检测字符串中是否包含子字符串 str,如果指定 beg(开始)和end(结束)范围,则检查是否包含在指定范围内,该方法与python find()方法一样,区别在于如果str不在 string中会报一个异常。
>>> help(str.index) Help on method_descriptor: index(...) S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found.
例:
>>> name = "python and python" >>> name.index("th") 2 >>> name.index("th",3) 13 >>> name.index("th", 3, 9) # 要查询的字符串不在指定范围内,报错。 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> name.index("th", 3, len(name)) 13 >>>
o. rindex
功能: 返回子字符串str在字符串中最后出现的位置,如果没有匹配的字符串会报异常,可以指定可选参数[beg:end]设置查找的区间。
>>> help(str.rindex) Help on method_descriptor: rindex(...) S.rindex(sub[, start[, end]]) -> int Like S.rfind() but raise ValueError when the substring is not found.
例:
>>> name = "python and python" >>> name.index("th") 2 >>> name.rindex("th") 13 >>> name.rindex("th", 0, 13) 2 >>> name.rindex("th", 4, 10) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>>
p. isnumeric
功能: 检测字符串是否只由数字组成。如果字符串中只包含数字字符,则返回 True,否则返回 False
>>> help(str.isnumeric) Help on method_descriptor: isnumeric(...) S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise.
例:
>>> name = "python2017" >>> name.isnumeric() False >>> name = "python" >>> name.isnumeric() False >>> name = "2017" >>> name.isnumeric() True >>> a = u‘123‘
注: 网上资料显示这种方法是只针对unicode对象,但是Python3默认为utf-8编码,并无报错。
q. islower
功能: 检测字符串是否由小写字母组成,结果返回布尔值。
>>> help(str.islower) Help on method_descriptor: islower(...) 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.
例:
>>> name = "Python" >>> name.islower() False >>> name = "python" >>> name.islower() True >>>
r. isspace
功能: 检测字符串是否只由空格组成。
>>> help(str.isspace) Help on method_descriptor: isspace(...) S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise.
例:
>>> name = " " >>> name.isspace() True >>> name = " s" >>> name.isspace() False >>>
s. istitle
功能: 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
>>> help(str.istitle) Help on method_descriptor: istitle(...) S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.
例:
>>> name = "python" >>> name.istitle() False >>> name = "Python" >>> name.istitle() True >>> name = "Python12" >>> name.istitle() True >>>
t. isupper
功能: 检测字符串中所有的字母是否都为大写。
>>> help(str.isupper) Help on method_descriptor: isupper(...) 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.
例:
>>> name = "Python" >>> name.isupper() False >>> name = "PYTHON" >>> name.isupper() True >>>
u. join
功能: 用于将序列中的元素以指定的字符连接生成一个新的字符串。
>>> help(str.join) Help on method_descriptor: join(...) S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.
例:
>>> n1 = "." >>> n2 = "@" >>> name = ("P", "y", "t", "h", "o", "n") >>> n1.join(name) ‘P.y.t.h.o.n‘ >>> n2.join(name) ‘[email protected]@[email protected]@[email protected]‘ >>>
v. replace
功能: 把字符串中的old(旧字符串)替换成new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
>>> help(str.replace) Help on method_descriptor: replace(...) S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
例:
>>> name = "This is a pet dog, It is very interesting!" >>> name ‘This is a pet dog, It is very interesting!‘ >>> name.replace("is", "was") ‘Thwas was a pet dog, It was very interesting!‘ >>> name.replace("is", "was", 2) ‘Thwas was a pet dog, It is very interesting!‘ # 设定替换不超过两次,则第三次没有被替换。 >>>
w. split
功能: 指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔 num 个子字符串.
>>> help(str.split) Help on method_descriptor: split(...) S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
例:
>>> name = "I‘m learning python" >>> name.split(" ") ["I‘m", ‘learning‘, ‘python‘] >>> name.split("n") ["I‘m lear", ‘i‘, ‘g pytho‘, ‘‘] >>> name.split("n",1) ["I‘m lear", ‘ing python‘] >>>
x. strip
功能: 用于移除字符串头尾指定的字符(默认为空格)。
>>> help(str.strip) Help on method_descriptor: strip(...) 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.
例:
>>> n1 = " Python" >>> n2 = "###Python###" >>> n1.strip() ‘Python‘ >>> n2.strip("#") ‘Python‘ >>>
---END.
本文出自 “yangbin” 博客,请务必保留此出处http://13683137989.blog.51cto.com/9636221/1911393
以上是关于Python基本数据类型的主要内容,如果未能解决你的问题,请参考以下文章