客官python包安装错误来这里

https://www.lfd.uci.edu/~gohlke/pythonlibs/

加快下载来这里

https://pypi.douban.com/simple

官方文档: https://docs.python.org

简介

1.动态、解释型号语言;开源

2.一切皆对象(即底层均为用对象实现,如内建函数的底层其实是通过对象实现的)。

3.强制缩进

技巧:1.双击Tab键可弹出对象非私有方法,如对象.+Tab两次;2.dir(对象)、vars(对象):查看对象的所有方法;3.help(对象.方法):方法的作用。

python的安装

Linux安装

说明:我的Centos6.8自带的python版本是2.6,原生python不支持自动补全,所以再安装一个ipython,ipython的版本和原生的python版本有对应

在线安装ipython:

先安安装出错提示No package pip available,Error: Nothing to do.先安装装扩展源:yum -y install epel-release

ip软件管理器(类似yum): yum install python-pip

安装ipython : pip install ipython==1.2.1

查看是否成功安装ipython:  pip list | grep ipython

windows安装

安装python解析器和IDE环境PyCharm(社区版是免费的,但只提供python环境,没有Django等框架,专业版收费提供很多框架)

https://www.python.org/downloads/windows/

https://www.jetbrains.com/pycharm/

这里的python采用python3(因为一些新特性只在python上有,接下来也用3,2.7是过渡版本,向后向前兼容但最新的3版本特性2会慢慢不支持,2.7版本将支持到2020年)

2.x和3.x的区别

2.x的除法就是取整,3正常四舍五入了

print "hello world"变成了print ("hello world")

raw_input变成了input

class B:变成了class B():

3用Unicode编码,默认支持中文了

3的range就是2里的xrange

操作文件,3按字符,2按字节

......

python 文件类型

.py源码  经编译==> .pyc字节码 .pyp优化字节码

用python编译代码(便编译的好处:1保护源码;2二进制文件执行更快):

import py_compile

py_compile.compile('.py')

变量

python的赋值均按引用传递

变量名由字母、数字(不能为首字符)、下划线组成,不能使用关键字

以下关键字不能声明为变量名 ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

id(变量)取得变量的地址

type(变量)取得变量的类型(类对象的类型为instance),type(类)取得类所在的路径

del 删除一个变量

特殊变量列表:sys.argv[n]

__name__ :当前文件直接执行时的值为main,被调用时的值为模块名

相等性比较

由于python所有类型均为引用类型,因此可以直接比较,没有所谓的装箱拆箱操作

"=="            比较值(适用于所有类型)
"is"(全等于)         同时比较值和地址(适用于所有类型) 

用户交互

name = input("please input your name:")print("i am %s" % name)

作用域

python和传统的C C++ JAVA C#等静态语言不同,区别在于前者采用的是函数作用域,后者采用的是括号作用域

注释

# 单行注释

''' ''' 或"""  """多行注释

运算符

算数运算

比较运算

逻辑运算

赋值运算

成员运算

成员测试:in,not in

身份运算

同一性测试:is.is not

位运算

按位反翻转:~

基本数据类型

1.按所占内存大小是否可变区分,不可变(开始指向的内存的值不能修改,元素个数也不变)

2.按是否是序列(有下标,如l=[a,b,c]的b下标是2)区分,序列支持索引和切片

序列的基本操作:

len() 求序列的长度+ 连接两个序列* 重复序列元素in 判断是否存在序列max() 最大值min() 最小值cmp(x,y) 比较两个序列是否相等

View Code

None

全局只有一个

a = None
b = None
res = a is b
print(res)  # True

数字

非序列、不可变

int

class int(object):"""int(x=0) -> integerint(x, base=10) -> integerConvert a number or string to an integer, or return 0 if no argumentsare given.  If x is a number, return x.__int__().  For floating pointnumbers, 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 thegiven base.  The literal can be preceded by '+' or '-' and be surroundedby 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"""def bit_length(self): # real signature unknown; restored from __doc__"""int.bit_length() -> intNumber of bits necessary to represent self in binary.>>> bin(37)'0b100101'>>> (37).bit_length()6"""return 0def conjugate(self, *args, **kwargs): # real signature unknown""" Returns self, the complex conjugate of any int. """pass@classmethod # known casedef from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """int.from_bytes(bytes, byteorder, *, signed=False) -> intReturn the integer represented by the given array of bytes.The bytes argument must be a bytes-like object (e.g. bytes or bytearray).The byteorder argument determines the byte order used to represent theinteger.  If byteorder is 'big', the most significant byte is at thebeginning of the byte array.  If byteorder is 'little', the mostsignificant byte is at the end of the byte array.  To request the nativebyte order of the host system, use `sys.byteorder' as the byte order value.The signed keyword-only argument indicates whether two's complement isused to represent the integer."""passdef to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """int.to_bytes(length, byteorder, *, signed=False) -> bytesReturn an array of bytes representing an integer.The integer is represented using length bytes.  An OverflowError israised if the integer is not representable with the given number ofbytes.The byteorder argument determines the byte order used to represent theinteger.  If byteorder is 'big', the most significant byte is at thebeginning of the byte array.  If byteorder is 'little', the mostsignificant byte is at the end of the byte array.  To request the nativebyte order of the host system, use `sys.byteorder' as the byte order value.The signed keyword-only argument determines whether two's complement isused to represent the integer.  If signed is False and a negative integeris given, an OverflowError is raised."""passdef __abs__(self, *args, **kwargs): # real signature unknown""" abs(self) """passdef __add__(self, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __and__(self, *args, **kwargs): # real signature unknown""" Return self&value. """passdef __bool__(self, *args, **kwargs): # real signature unknown""" self != 0 """passdef __ceil__(self, *args, **kwargs): # real signature unknown""" Ceiling of an Integral returns itself. """passdef __divmod__(self, *args, **kwargs): # real signature unknown""" Return divmod(self, value). """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __float__(self, *args, **kwargs): # real signature unknown""" float(self) """passdef __floordiv__(self, *args, **kwargs): # real signature unknown""" Return self//value. """passdef __floor__(self, *args, **kwargs): # real signature unknown""" Flooring an Integral returns itself. """passdef __format__(self, *args, **kwargs): # real signature unknownpassdef __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __hash__(self, *args, **kwargs): # real signature unknown""" Return hash(self). """passdef __index__(self, *args, **kwargs): # real signature unknown""" Return self converted to an integer, if self is suitable for use as an index into a list. """passdef __init__(self, x, base=10): # known special case of int.__init__"""int(x=0) -> integerint(x, base=10) -> integerConvert a number or string to an integer, or return 0 if no argumentsare given.  If x is a number, return x.__int__().  For floating pointnumbers, 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 thegiven base.  The literal can be preceded by '+' or '-' and be surroundedby 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# (copied from class doc)"""passdef __int__(self, *args, **kwargs): # real signature unknown""" int(self) """passdef __invert__(self, *args, **kwargs): # real signature unknown""" ~self """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lshift__(self, *args, **kwargs): # real signature unknown""" Return self<<value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mod__(self, *args, **kwargs): # real signature unknown""" Return self%value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """passdef __neg__(self, *args, **kwargs): # real signature unknown""" -self """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __or__(self, *args, **kwargs): # real signature unknown""" Return self|value. """passdef __pos__(self, *args, **kwargs): # real signature unknown""" +self """passdef __pow__(self, *args, **kwargs): # real signature unknown""" Return pow(self, value, mod). """passdef __radd__(self, *args, **kwargs): # real signature unknown""" Return value+self. """passdef __rand__(self, *args, **kwargs): # real signature unknown""" Return value&self. """passdef __rdivmod__(self, *args, **kwargs): # real signature unknown""" Return divmod(value, self). """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __rfloordiv__(self, *args, **kwargs): # real signature unknown""" Return value//self. """passdef __rlshift__(self, *args, **kwargs): # real signature unknown""" Return value<<self. """passdef __rmod__(self, *args, **kwargs): # real signature unknown""" Return value%self. """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return value*self. """passdef __ror__(self, *args, **kwargs): # real signature unknown""" Return value|self. """passdef __round__(self, *args, **kwargs): # real signature unknown"""Rounding an Integral returns itself.Rounding with an ndigits argument also returns an integer."""passdef __rpow__(self, *args, **kwargs): # real signature unknown""" Return pow(value, self, mod). """passdef __rrshift__(self, *args, **kwargs): # real signature unknown""" Return value>>self. """passdef __rshift__(self, *args, **kwargs): # real signature unknown""" Return self>>value. """passdef __rsub__(self, *args, **kwargs): # real signature unknown""" Return value-self. """passdef __rtruediv__(self, *args, **kwargs): # real signature unknown""" Return value/self. """passdef __rxor__(self, *args, **kwargs): # real signature unknown""" Return value^self. """passdef __sizeof__(self, *args, **kwargs): # real signature unknown""" Returns size in memory, in bytes """passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """passdef __sub__(self, *args, **kwargs): # real signature unknown""" Return self-value. """passdef __truediv__(self, *args, **kwargs): # real signature unknown""" Return self/value. """passdef __trunc__(self, *args, **kwargs): # real signature unknown""" Truncating an Integral returns itself. """passdef __xor__(self, *args, **kwargs): # real signature unknown""" Return self^value. """passdenominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default"""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"""

View Code

float

class float(object):"""float(x) -> floating point numberConvert a string or number to a floating point number, if possible."""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 originalfloat 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)"""passdef conjugate(self, *args, **kwargs): # real signature unknown""" Return self, the complex conjugate of any float. """passdef fromhex(self, string): # real signature unknown; restored from __doc__"""float.fromhex(string) -> floatCreate a floating-point number from a hexadecimal string.>>> float.fromhex('0x1.ffffp10')2047.984375>>> float.fromhex('-0x1p-1074')-5e-324"""return 0.0def hex(self): # real signature unknown; restored from __doc__"""float.hex() -> stringReturn a hexadecimal representation of a floating-point number.>>> (-0.1).hex()'-0x1.999999999999ap-4'>>> 3.14159.hex()'0x1.921f9f01b866ep+1'"""return ""def is_integer(self, *args, **kwargs): # real signature unknown""" Return True if the float is an integer. """passdef __abs__(self, *args, **kwargs): # real signature unknown""" abs(self) """passdef __add__(self, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __bool__(self, *args, **kwargs): # real signature unknown""" self != 0 """passdef __divmod__(self, *args, **kwargs): # real signature unknown""" Return divmod(self, value). """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __float__(self, *args, **kwargs): # real signature unknown""" float(self) """passdef __floordiv__(self, *args, **kwargs): # real signature unknown""" Return self//value. """passdef __format__(self, format_spec): # real signature unknown; restored from __doc__"""float.__format__(format_spec) -> stringFormats the float according to format_spec."""return ""def __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getformat__(self, typestr): # real signature unknown; restored from __doc__"""float.__getformat__(typestr) -> stringYou probably don't want to use this function.  It exists mainly to beused in Python's test suite.typestr must be 'double' or 'float'.  This function returns whichever of'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes theformat of floating point numbers used by the C type named by typestr."""return ""def __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __hash__(self, *args, **kwargs): # real signature unknown""" Return hash(self). """passdef __init__(self, x): # real signature unknown; restored from __doc__passdef __int__(self, *args, **kwargs): # real signature unknown""" int(self) """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mod__(self, *args, **kwargs): # real signature unknown""" Return self%value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """passdef __neg__(self, *args, **kwargs): # real signature unknown""" -self """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __pos__(self, *args, **kwargs): # real signature unknown""" +self """passdef __pow__(self, *args, **kwargs): # real signature unknown""" Return pow(self, value, mod). """passdef __radd__(self, *args, **kwargs): # real signature unknown""" Return value+self. """passdef __rdivmod__(self, *args, **kwargs): # real signature unknown""" Return divmod(value, self). """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __rfloordiv__(self, *args, **kwargs): # real signature unknown""" Return value//self. """passdef __rmod__(self, *args, **kwargs): # real signature unknown""" Return value%self. """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return value*self. """passdef __round__(self, *args, **kwargs): # real signature unknown"""Return the Integral closest to x, rounding half toward even.When an argument is passed, work like built-in round(x, ndigits)."""passdef __rpow__(self, *args, **kwargs): # real signature unknown""" Return pow(value, self, mod). """passdef __rsub__(self, *args, **kwargs): # real signature unknown""" Return value-self. """passdef __rtruediv__(self, *args, **kwargs): # real signature unknown""" Return value/self. """passdef __setformat__(self, typestr, fmt): # real signature unknown; restored from __doc__"""float.__setformat__(typestr, fmt) -> NoneYou probably don't want to use this function.  It exists mainly to beused in Python's test suite.typestr must be 'double' or 'float'.  fmt must be one of 'unknown','IEEE, big-endian' or 'IEEE, little-endian', and in addition can only beone of the latter two if it appears to match the underlying C reality.Override the automatic determination of C-level floating point type.This affects how floats are converted to and from binary strings."""passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """passdef __sub__(self, *args, **kwargs): # real signature unknown""" Return self-value. """passdef __truediv__(self, *args, **kwargs): # real signature unknown""" Return self/value. """passdef __trunc__(self, *args, **kwargs): # real signature unknown""" Return the Integral closest to x between 0 and x. """passimag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default"""the imaginary part of a complex number"""real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default"""the real part of a complex number"""

View Code

字符串

序列、不可变

方法:

class str(object):"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to 'strict'."""def capitalize(self): # real signature unknown; restored from __doc__"""S.capitalize() -> strReturn a capitalized version of S, i.e. make the first characterhave upper case and the rest lower case."""return ""def casefold(self): # real signature unknown; restored from __doc__"""S.casefold() -> strReturn a version of S suitable for caseless comparisons."""return ""def center(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.center(width[, fillchar]) -> strReturn 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): # real signature unknown; restored from __doc__"""S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end].  Optional arguments start and end areinterpreted as in slice notation."""return 0def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__"""S.encode(encoding='utf-8', errors='strict') -> bytesEncode S using the codec registered for encoding. Default encodingis 'utf-8'. 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 can handle UnicodeEncodeErrors."""return b""def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__"""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=8): # real signature unknown; restored from __doc__"""S.expandtabs(tabsize=8) -> strReturn 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): # real signature unknown; restored from __doc__"""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(self, *args, **kwargs): # known special case of str.format"""S.format(*args, **kwargs) -> strReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}')."""passdef format_map(self, mapping): # real signature unknown; restored from __doc__"""S.format_map(mapping) -> strReturn a formatted version of S, using substitutions from mapping.The substitutions are identified by braces ('{' and '}')."""return ""def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.index(sub[, start[, end]]) -> intLike S.find() but raise ValueError when the substring is not found."""return 0def isalnum(self): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise."""return Falsedef isdecimal(self): # real signature unknown; restored from __doc__"""S.isdecimal() -> boolReturn True if there are only decimal characters in S,False otherwise."""return Falsedef isdigit(self): # real signature unknown; restored from __doc__"""S.isdigit() -> boolReturn True if all characters in S are digitsand there is at least one character in S, False otherwise."""return Falsedef isidentifier(self): # real signature unknown; restored from __doc__"""S.isidentifier() -> boolReturn True if S is a valid identifier accordingto the language definition.Use keyword.iskeyword() to test for reserved identifierssuch as "def" and "class"."""return Falsedef islower(self): # real signature unknown; restored from __doc__"""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 isnumeric(self): # real signature unknown; restored from __doc__"""S.isnumeric() -> boolReturn True if there are only numeric characters in S,False otherwise."""return Falsedef isprintable(self): # real signature unknown; restored from __doc__"""S.isprintable() -> boolReturn True if all characters in S are consideredprintable in repr() or S is empty, False otherwise."""return Falsedef isspace(self): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.istitle() -> boolReturn True if S is a titlecased string and there is at least onecharacter in S, i.e. upper- and titlecase characters may onlyfollow uncased characters and lowercase characters only cased ones.Return False otherwise."""return Falsedef isupper(self): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.join(iterable) -> strReturn a string which is the concatenation of the strings in theiterable.  The separator between elements is S."""return ""def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.ljust(width[, fillchar]) -> strReturn S left-justified in a Unicode string of length width. Padding isdone using the specified fill character (default is a space)."""return ""def lower(self): # real signature unknown; restored from __doc__"""S.lower() -> strReturn a copy of the string S converted to lowercase."""return ""def lstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.lstrip([chars]) -> strReturn a copy of the string S with leading whitespace removed.If chars is given and not None, remove characters in chars instead."""return ""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 Unicodeordinals (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, andin the resulting dictionary, each character in x will be mapped to thecharacter at the same position in y. If there is a third argument, itmust be a string, whose characters will be mapped to None in the result."""passdef partition(self, sep): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.replace(old, new[, count]) -> strReturn a copy of 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): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.rindex(sub[, start[, end]]) -> intLike S.rfind() but raise ValueError when the substring is not found."""return 0def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.rjust(width[, fillchar]) -> strReturn 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): # real signature unknown; restored from __doc__"""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=-1): # real signature unknown; restored from __doc__"""S.rsplit(sep=None, maxsplit=-1) -> list of stringsReturn a list of the words in S, using sep as thedelimiter string, starting at the end of the string andworking to the front.  If maxsplit is given, at most maxsplitsplits are done. If sep is not specified, any whitespace stringis a separator."""return []def rstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.rstrip([chars]) -> strReturn a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead."""return ""def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__"""S.split(sep=None, maxsplit=-1) -> list of stringsReturn a list of the words in 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 areremoved from the result."""return []def splitlines(self, keepends=None): # real signature unknown; restored from __doc__"""S.splitlines([keepends]) -> 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): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.strip([chars]) -> strReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead."""return ""def swapcase(self): # real signature unknown; restored from __doc__"""S.swapcase() -> strReturn a copy of S with uppercase characters converted to lowercaseand vice versa."""return ""def title(self): # real signature unknown; restored from __doc__"""S.title() -> strReturn a titlecased version of S, i.e. words start with title casecharacters, all remaining cased characters have lower case."""return ""def translate(self, table): # real signature unknown; restored from __doc__"""S.translate(table) -> strReturn a copy of the string S in which each character has been mappedthrough the given translation table. The table must implementlookup/indexing via __getitem__, for instance a dictionary or list,mapping Unicode ordinals to Unicode ordinals, strings, or None. Ifthis operation raises LookupError, the character is left untouched.Characters mapped to None are deleted."""return ""def upper(self): # real signature unknown; restored from __doc__"""S.upper() -> strReturn a copy of S converted to uppercase."""return ""def zfill(self, width): # real signature unknown; restored from __doc__"""S.zfill(width) -> strPad a numeric string S with zeros on the left, to fill a fieldof the specified width. The string S is never truncated."""return ""def __add__(self, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __contains__(self, *args, **kwargs): # real signature unknown""" Return key in self. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __format__(self, format_spec): # real signature unknown; restored from __doc__"""S.__format__(format_spec) -> strReturn a formatted version of S as described by format_spec."""return ""def __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getitem__(self, *args, **kwargs): # real signature unknown""" Return self[key]. """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __hash__(self, *args, **kwargs): # real signature unknown""" Return hash(self). """passdef __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to 'strict'.# (copied from class doc)"""passdef __iter__(self, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mod__(self, *args, **kwargs): # real signature unknown""" Return self%value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value.n """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __rmod__(self, *args, **kwargs): # real signature unknown""" Return value%self. """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" S.__sizeof__() -> size of S in memory, in bytes """passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """pass

View Code

字符串格式化

Python的字符串格式化有两种方式: 百分号方式、format方式

百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存

 1、百分号方式

%[(name)][flags][width].[precision]typecode

(name)      可选,用于选择指定的key
flags          可选,可供选择的值有:+       右对齐;正数前加正好,负数前加负号;-        左对齐;正数前无符号,负数前加负号;空格    右对齐;正数前加空格,负数前加负号;0        右对齐;正数前无符号,负数前加负号;用0填充空白处
width         可选,占有宽度
.precision   可选,小数点后保留的位数
typecode    必选s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置o,将整数转换成 八  进制表示,并将其格式化到指定位置x,将整数转换成十六进制表示,并将其格式化到指定位置d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
F,同上g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
%,当字符串中存在格式化标志时,需要用 %%表示一个百分号

View Code

常用格式化:

tpl = "i am %s" % "alex"tpl = "i am %s age %d" % ("alex", 18)tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}tpl = "percent %.2f" % 99.97623tpl = "i am %(pp).2f" % {"pp": 123.425556, }tpl = "i am %.2f %%" % {"pp": 123.425556, }

2、Format方式

[[fill]align][sign][#][0][width][,][.precision][type]

fill           【可选】空白处填充的字符
align        【可选】对齐方式(需配合width使用)<,内容左对齐>,内容右对齐(默认)=,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字^,内容居中
sign         【可选】有无符号数字+,正号加正,负号加负;-,正号不变,负号加负;空格 ,正号空格,负号加负;
#            【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
,            【可选】为数字添加分隔符,如:1,000,000
width       【可选】格式化位所占宽度
.precision 【可选】小数位保留精度
type         【可选】格式化类型传入” 字符串类型 “的参数s,格式化字符串类型数据空白,未指定类型,则默认是None,同s传入“ 整数类型 ”的参数b,将10进制整数自动转换成2进制表示然后格式化c,将10进制整数自动转换为其对应的unicode字符d,十进制整数o,将10进制整数自动转换成8进制表示然后格式化;x,将10进制整数自动转换成16进制表示然后格式化(小写x)X,将10进制整数自动转换成16进制表示然后格式化(大写X)传入“ 浮点型或小数类型 ”的参数e, 转换为科学计数法(小写e)表示,然后格式化;E, 转换为科学计数法(大写E)表示,然后格式化;f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;g, 自动在e和f中切换G, 自动在E和F中切换%,显示百分比(默认显示小数点后6位)

View Code

常用格式化:

tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])tpl = "i am {0}, age {1}, really {0}".format("seven", 18)tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)tpl = "i am {:s}, age {:d}".format(*["seven", 18])tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

更多格式化操作:https://docs.python.org/3/library/string.html

元组

序列、不可变  //可看作不可变数组;注意:如果只有一个元素,要有逗号

class 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, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __contains__(self, *args, **kwargs): # real signature unknown""" Return key in self. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getitem__(self, *args, **kwargs): # real signature unknown""" Return self[key]. """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __hash__(self, *args, **kwargs): # real signature unknown""" Return hash(self). """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, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value.n """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """pass

View Code

创建空元组:

t=tuple()

t=()

元组的拆分

 1 In [17]: t1=(1,2,3,4,5)
 2
 3 In [18]: t1=(1,2,3)
 4
 5 In [19]: a,b,c = t1
 6
 7 In [20]: a,b,c
 8 Out[20]: (1, 2, 3)
 9
10 In [21]: a
11 Out[21]: 1
12
13 In [22]: b
14 Out[22]: 2
15
16 In [23]: c
17 Out[23]: 3

View Code

 列表

[]:序列、可变 //可看作数组

方法

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) -> None -- append object to end """passdef clear(self): # real signature unknown; restored from __doc__""" L.clear() -> None -- remove all items from L """passdef copy(self): # real signature unknown; restored from __doc__""" L.copy() -> list -- a shallow copy of L """return []def 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) -> None -- 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) -> None -- 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, key=None, reverse=False): # real signature unknown; restored from __doc__""" L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """passdef __add__(self, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __contains__(self, *args, **kwargs): # real signature unknown""" Return key in self. """passdef __delitem__(self, *args, **kwargs): # real signature unknown""" Delete self[key]. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __iadd__(self, *args, **kwargs): # real signature unknown""" Implement self+=value. """passdef __imul__(self, *args, **kwargs): # real signature unknown""" Implement self*=value. """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, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value.n """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __reversed__(self): # real signature unknown; restored from __doc__""" L.__reversed__() -- return a reverse iterator over the list """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """passdef __setitem__(self, *args, **kwargs): # real signature unknown""" Set self[key] to value. """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" L.__sizeof__() -- size of L in memory, in bytes """pass__hash__ = None

View Code

创建列表对象:

l=[]

l=list()

 字典

非序列、可变,

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(*args, **kwargs): # real signature unknown""" Returns a new dict with keys from iterable and values equal to value. """passdef get(self, k, d=None): # real signature unknown; restored from __doc__""" D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """passdef items(self): # real signature unknown; restored from __doc__""" D.items() -> a set-like object providing a view on D's items """passdef keys(self): # real signature unknown; restored from __doc__""" D.keys() -> a set-like object providing a view on D's keys """passdef 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__""" 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"""D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]If E is present and lacks a .keys() method, then 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() -> an object providing a view on D's values """passdef __contains__(self, *args, **kwargs): # real signature unknown""" True if D has a key k, else False. """passdef __delitem__(self, *args, **kwargs): # real signature unknown""" Delete self[key]. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """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, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __setitem__(self, *args, **kwargs): # real signature unknown""" Set self[key] to value. """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" D.__sizeof__() -> size of D in memory, in bytes """pass__hash__ = None

View Code

创建字典对象:

l={}

l=dict()

字典的key要求是不可变类型

集合

非序列、可变,元素不重复

class set(object):"""set() -> new empty set objectset(iterable) -> new set objectBuild an unordered collection of unique elements."""def add(self, *args, **kwargs): # real signature unknown"""Add an element to a set.This has no effect if the element is already present."""passdef clear(self, *args, **kwargs): # real signature unknown""" Remove all elements from this set. """passdef copy(self, *args, **kwargs): # real signature unknown""" Return a shallow copy of a set. """passdef difference(self, *args, **kwargs): # real signature unknown"""Return the difference of two or more sets as a new set.(i.e. all elements that are in this set but not the others.)"""passdef difference_update(self, *args, **kwargs): # real signature unknown""" Remove all elements of another set from this set. """passdef discard(self, *args, **kwargs): # real signature unknown"""Remove an element from a set if it is a member.If the element is not a member, do nothing."""passdef intersection(self, *args, **kwargs): # real signature unknown"""Return the intersection of two sets as a new set.(i.e. all elements that are in both sets.)"""passdef intersection_update(self, *args, **kwargs): # real signature unknown""" Update a set with the intersection of itself and another. """passdef isdisjoint(self, *args, **kwargs): # real signature unknown""" Return True if two sets have a null intersection. """passdef issubset(self, *args, **kwargs): # real signature unknown""" Report whether another set contains this set. """passdef issuperset(self, *args, **kwargs): # real signature unknown""" Report whether this set contains another set. """passdef pop(self, *args, **kwargs): # real signature unknown"""Remove and return an arbitrary set element.Raises KeyError if the set is empty."""passdef remove(self, *args, **kwargs): # real signature unknown"""Remove an element from a set; it must be a member.If the element is not a member, raise a KeyError."""passdef symmetric_difference(self, *args, **kwargs): # real signature unknown"""Return the symmetric difference of two sets as a new set.(i.e. all elements that are in exactly one of the sets.)"""passdef symmetric_difference_update(self, *args, **kwargs): # real signature unknown""" Update a set with the symmetric difference of itself and another. """passdef union(self, *args, **kwargs): # real signature unknown"""Return the union of sets as a new set.(i.e. all elements that are in either set.)"""passdef update(self, *args, **kwargs): # real signature unknown""" Update a set with the union of itself and others. """passdef __and__(self, *args, **kwargs): # real signature unknown""" Return self&value. """passdef __contains__(self, y): # real signature unknown; restored from __doc__""" x.__contains__(y) <==> y in x. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __iand__(self, *args, **kwargs): # real signature unknown""" Return self&=value. """passdef __init__(self, seq=()): # known special case of set.__init__"""set() -> new empty set objectset(iterable) -> new set objectBuild an unordered collection of unique elements.# (copied from class doc)"""passdef __ior__(self, *args, **kwargs): # real signature unknown""" Return self|=value. """passdef __isub__(self, *args, **kwargs): # real signature unknown""" Return self-=value. """passdef __iter__(self, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __ixor__(self, *args, **kwargs): # real signature unknown""" Return self^=value. """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __or__(self, *args, **kwargs): # real signature unknown""" Return self|value. """passdef __rand__(self, *args, **kwargs): # real signature unknown""" Return value&self. """passdef __reduce__(self, *args, **kwargs): # real signature unknown""" Return state information for pickling. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __ror__(self, *args, **kwargs): # real signature unknown""" Return value|self. """passdef __rsub__(self, *args, **kwargs): # real signature unknown""" Return value-self. """passdef __rxor__(self, *args, **kwargs): # real signature unknown""" Return value^self. """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" S.__sizeof__() -> size of S in memory, in bytes """passdef __sub__(self, *args, **kwargs): # real signature unknown""" Return self-value. """passdef __xor__(self, *args, **kwargs): # real signature unknown""" Return self^value. """pass__hash__ = None

View Code

创建集合对象

s=set()

队列

双向队列collections.deque

append  extend  leftremove  append  leftmrorotate  clear  pop   extend  popleft

单向队列queue.Queue

all_tasks_done   get_nowait   not_empty   qsize   empty    join    not_full    queue

full    maxsize    put task_done   get    mutex    put_nowait    unfinished_tasks

类型、进制转换

类型转换

字符串与数字互转

In [13]: a=1In [14]: stra = str(a)In [15]: stra
Out[15]: '1'In [16]: inta = int(stra)In [17]: inta
Out[17]: 1

字符串转列表|元组|字典(eval去除外部字符串)

s='abc't=tuple(s)
('a', 'b', 'c')l=list(s)
['a', 'b', 'c']eval("('a','b','c')")
('a', 'b', 'c')eval("['a','b','c']")
['a', 'b', 'c']eval("{'name':'hy', 'age':24}")
{'age': 24, 'name': 'hy'}

列表|元组转字符串

 ''.join(l)'abc'','.join(l)
'a,b,c'

str(t)
"('a', 'b', 'c')"str(l)
"['a', 'b', 'c']"str(d)
"{'a': 1, 'b': 2}"

列表转元组

l=[1,2,3,]
t=tuple(l)
print(t)
(1,2,3)

元组转列表

t=(1,2,3,)
l=list(t)
print(l)
[1, 2, 3]

字典转列表

d={'a': 1, 'b': 2}d.values()
[1, 2]

字典转元组

d={'a': 1, 'b': 2}
tuple(dict.values())

字符串转字节(python3)

In [1]: s='中文'In [2]: s
Out[2]: '中文'In [3]: type(s)
Out[3]: strIn [4]: b = bytes(s, encoding='utf-8')In [5]: b
Out[5]: b'\xe4\xb8\xad\xe6\x96\x87'In [6]: type(b)
Out[6]: bytes

字节转字符串(python3)

In [7]: s1=str(b)In [8]: s1
Out[8]: "b'\\xe4\\xb8\\xad\\xe6\\x96\\x87'"In [9]: type(s1)
Out[9]: strIn [10]: s1 = str(b, encoding='utf-8')In [11]: s1
Out[11]: '中文'In [12]: type(s1)
Out[12]: str

遍历

遍历列表|元组

t=('a', 'b', 'c')for v in t:print(v)
a
b
cfor k,v in enumerate(t):print(k, v)
(0, 'a')
(1, 'b')
(2, 'c')l=['a', 'b', 'c']for v in l:print(v)
a
b
cfor k,v in enumerate(l):print(k, v)
(0, 'a')
(1, 'b')
(2, 'c')

遍历字典 

d =  {'a': 1, 'b': 2}for v in d:print(v)
a
bfor v in d.values():print(v)
1
2for k,v in d.items():print(k,v)
('a', 1)
('b', 2)for k,v in zip(d.keys(),d.values()):print(k,v)
('a', 1)
('b', 2)

进制转换

In [2]:  bin(8)
Out[2]: '0b1000'In [3]: int("1001",2)
Out[3]: 9In [4]: hex(10)
Out[4]: '0xa'In [5]: int('xa', 16)

字面常量池

所谓字面,就是我们在程序中直接以值的行式来操作、表现(可以对照变量);
所谓常量,是指这些值不能再被改变了。

在Python中,对字面常量(数字、字符串、布尔、字节)对象进行缓存:

In [1]: a=1In [2]: b=1In [3]: a is b
Out[3]: TrueIn [4]: s1='hi'In [5]: s2='hi'In [6]: s1 is s2
Out[6]: TrueIn [7]: L1 = [1]In [8]: L2=[1]In [9]: L1 is L2
Out[9]: False 

Python仅仅对比较小的整数对象进行缓存(范围为范围[-5, 256])缓存起来,而并非是所有整数对象

b = 256
a = 256
a is b
Out[24]: True
a = 257
b = 257
a is b
Out[27]: False

hour_min_sec = ['123456', '54', '08']
hour_min_sec_min = ['1234', '54', '08']
hour_min_sec_small = ['123', '54', '08']print(id( int(hour_min_sec[0])))
print(id(123456), end='\n\n')print(id( int(hour_min_sec_min[0])))
print(id(1234) , end='\n\n')print(id( int(hour_min_sec_small[0])))
print(id(123))'''输出
1291546658320
12915621468001291542965968
12915640603361792768896
1792768896
'''

  

编码

参考 python字符编码

编码的发展历史

 ASCII:美国的编码,计算机起源于美国,开始网络也没有,计算机的语言和人类语言是不一样的,计算机实际就是用0和1来的组成来表示人来语言的,而美国的语言是英语,文字由字母、数字和英语字符构成,因此,用8个数字(8bit,也就是一个字节即1byte)就可以表示2的8次方个(256种)字符,英语单词目前有几万个,但是不到2的16次方(65536)种形式,因为英语由26个字母组成,计算机不需要表示单词,直接用单个字母表示,26个字母加上一些标点等符号,形式不到256种,因此(8bit)256种形式就能满足需求。

当计算机发展到今天,出现两个问题:

1不同国家有不同的语言,拿我们现代汉语举例,我们的现代汉语用单个字母无法表示,因为我们的汉子是笔划组成的,所以有多少汉字就要有多少种形式,新华字典收录的现代汉子就有近11000种,所以,至少需要14个bit(16384)来表示,因此,我们国家自己采用了一套GBK标准(16bit,之所以不采用14或15bit是因为计算机的基本组成单位是8bit即1字节,GBK在ASCII的基础上往后补充汉字),,问题解决了。但是新问题又来了,随着使用计算机的国家越来越多,各自的国家均各自也弄了一套自己语言文字的编码标准,后面出现网络的时候,不同的国家要互相沟通,就没有一个编码标准了,我们这边的"你好",假设用0000000010101010 表示 , 发送美国那边0000000010101010对应的是乱码,人家没有这个位置的字符,到1994年,Unicode出现了,Unicode采用16bit(65536)来统一编码标准,包含了ASCII编码,世界上英语母语国家居多,用几百个字符就够玩了,兼容还不忘自己的ASCI(算了,毕竟人家发明的计算机),后面一些bit就是世界上一些用的起计算机的土豪国家语言的编码,标准的问题解决了,英语母语的国家不高兴了。

2.Unicode对所有字符采用2byte(16bit)来表示一个字符,那么问题来了,如果数据存在大量的英文字母,用Unicode就多了近一倍的空间,即存储和传输的空间就多了一倍,那英语国家为了解决这个问题,出现了另外一种可变长的编码:utf-8,英文用8bit表示,其它语言用8nbit表示,比如现代汉字,常用汉字用3个字节表示,生僻字用4-6个字节表示。utf-8在内存中会自动使用Unicode编码因为内存不支持utf-8编码,因此utf-8编码对存储或传输大量英文的需求作用明显。

总结:

1.当我们中国人用电子设备(如电脑)工作时,程序员和普通办公人员的不同在于,普通办公人员遇到的编码问题是操作系统带来的问题(windows默认编码gbk,linux默认编码utf8),而程序员除了这个问题,还有程序解释器带来的问题。比如普通办公人员使用windows系统打开word文档按照gbk来解码,python程序员用IDE默认的编码方式完成编码后,重新打开文件载入代码到内存是按照IDE的默认解码方式,执行python程序时python解释器按照指定的解码方式执行代码(python2默认是ascii解码,python3是utf8解码),也就是说,这个python程序员遇到操作系统的代码编码、python解释器载入代码到内存的解码、python解释器解析python数据类型的解码共三次编码问题。

2.内存的编码使用unicode,不代表内存中全都是unicode。

如代码x="egon"

在程序执行之前,内存中确实都是unicode,比如从文件中读取了一行x="egon",其中的x,等号,引号,地位都一样,都是普通字符而已,都是以unicode的格式存放于内存中的

但是程序在执行过程中,会申请内存(与程序代码所存在的内存是俩个空间)用来存放python的数据类型的值,而python的字符串类型又涉及到了字符的概念

比如x="egon",会被python解释器识别为字符串,会申请内存空间来存放字符串类型的值,至于该字符串类型的值被识别成何种编码存放,这就与python解释器的有关了,而python2与python3的字符串类型又有所不同。

直接赋值、浅拷贝和深度拷贝

简介

直接赋值:其实就是对象的引用(别名)。
浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。
深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。

详解 

>>>a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})

  

>>>import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})

1、b = a: 赋值引用,a 和 b 都指向同一个对象。

2、b = a.copy(): 浅拷贝, a 和 b 是一个独立的对象,但他们的子对象还是指向统一对象(是引用)。

3.b = copy.deepcopy(a): 深度拷贝, a 和 b 完全拷贝了父对象及其子对象,两者是完全独立的。

其它示例

#!/usr/bin/python
# -*-coding:utf-8 -*-import copya = [1, 2, 3, ['a', 'b']]  # 原始对象

b = a  # 赋值,传对象的引用
c = copy.copy(a)  # 对象拷贝,浅拷贝
d = copy.deepcopy(a)  # 对象拷贝,深拷贝

a.append(4)  # 修改对象a
a[3].append('c')  # 修改对象a中的['a', 'b']数组对象print('a = ', a)
print('b = ', b)
print('c = ', c)
print('d = ', d)//输出
a =  [1, 2, 3, ['a', 'b', 'c'], 4]
b =  [1, 2, 3, ['a', 'b', 'c'], 4]
c =  [1, 2, 3, ['a', 'b', 'c']]
d =  [1, 2, 3, ['a', 'b']]  

demo1

#!/usr/bin/python
# -*-coding:utf-8 -*-import copya = [1, 2, 3, ['a', 'b', [4, 5, 6]]]  # 原始对象

b = a  # 赋值,传对象的引用
c = copy.copy(a)  # 对象拷贝,浅拷贝
d = copy.deepcopy(a)  # 对象拷贝,深拷贝

a.append(4)  # 修改对象a
a[3].append('c')  # 修改对象a中的['a', 'b']数组对象
a[3][2].append(7)print('a = ', a)
print('b = ', b)
print('c = ', c)
print('d = ', d)//输出
a =  [1, 2, 3, ['a', 'b', [4, 5, 6, 7], 'c'], 4]
b =  [1, 2, 3, ['a', 'b', [4, 5, 6, 7], 'c'], 4]
c =  [1, 2, 3, ['a', 'b', [4, 5, 6, 7], 'c']]
d =  [1, 2, 3, ['a', 'b', [4, 5, 6]]]

demo2

转载于:https://www.cnblogs.com/hyit/articles/6275693.html

python【第一篇】基础相关推荐

  1. Webpack系列-第一篇基础杂记

    系列文章 Webpack系列-第一篇基础杂记 Webpack系列-第二篇插件机制杂记 Webpack系列-第三篇流程杂记 前言 公司的前端项目基本都是用Webpack来做工程化的,而Webpack虽然 ...

  2. 重温《数据库系统概论》【第一篇 基础篇】【第5章 数据库完整性】

    本篇内容为中国人民大学教授王珊.萨师煊的<数据库系统概论>自学课程的复习笔记,学习视频源于小破站(传送门),对应视频P32-P36,属教材"[第一篇 基础篇]"的&qu ...

  3. 重温《数据库系统概论》【第一篇 基础篇】【第4章 数据库安全性】

    本篇内容为中国人民大学教授王珊.萨师煊的<数据库系统概论>自学课程的复习笔记,学习视频源于小破站(传送门),对应视频P28-P31,属教材"[第一篇 基础篇]"的&qu ...

  4. 重温《数据库系统概论》【第一篇 基础篇】【第3章 关系数据库标准语言SQL】

    本篇内容为中国人民大学教授王珊.萨师煊的<数据库系统概论>自学课程的复习笔记,学习视频源于小破站(传送门),对应视频P16-P27,属教材"[第一篇 基础篇]"的&qu ...

  5. 重温《数据库系统概论》【第一篇 基础篇】【第2章 关系数据库】

    本篇内容为中国人民大学教授王珊.萨师煊的<数据库系统概论>自学课程的复习笔记,学习视频源于小破站(传送门),对应视频P9-P15,属教材"[第一篇 基础篇]"的&quo ...

  6. 重温《数据库系统概论》【第一篇 基础篇】【第1章 绪论】

    时隔两年,重温数据库,再次学习人大教授王珊.萨师煊的<数据库系统概论>,别有一番滋味在心头,或许这就是软件"不归路"上的感悟吧,又一次打开课本,记忆犹新,在已经学习过大 ...

  7. zabbix监控第一篇---基础使用

    zabbix监控系统第一篇---安装和简单使用 在本文中主要讲一下目前比较流行的zabbix监控系统的安装和使用,实验以最新的zabbix版本为准. 1. 监控系统简介: 业界常用的监控系统主要包括N ...

  8. 【python第一章 基础捋顺,第二章 python基础语法】

    第一章 基础捋顺,第二章 python基础语法 第一章 基础捋顺 第二章 python基础语法 2.1输入输出 2.2代码注释 2.3代码缩进 2.4命名规范 2.5变量 2.6基本数据类型 2.7数 ...

  9. [Python笔记]第一篇:基础知识

    本篇主要内容有:什么是python.如何安装python.py解释器解释过程.字符集转换知识.传参.流程控制 初识Python 一.什么是Python Python是一种面向对象.解释型计算机程序设计 ...

  10. Python开发第一篇 基础篇(下)

    一.python种类 1.1 Cpython python官方版本,使用c语言实现,运行机制:先编译,py(源码文件)->pyc(字节码文件),最终执行时先将字节码转换成机器码,然后交给cpu执 ...

最新文章

  1. 负载均衡续:万亿流量场景下的负载均衡实践
  2. C++使用数组实现queue之一(附完整源码)
  3. 编译php ./configure命令enable和with有什么区别
  4. 湖南大学计算机考研考什么,2017年湖南大学计算机系统考研大纲
  5. [剑指offer]面试题第[66]题[构建乘积数组][Leetcode][JAVA][第238题][除自身以外数组的乘积][数组]
  6. 卓有成效的管理者--总结
  7. FTP下载多个文件打包成一个压缩包
  8. 如何制作个人网站(如何搭建个人博客)
  9. CAN 通信协议(希望大家多多指点)
  10. 一套价值800元的爱代挂源码完整版
  11. 数据结构 | 哈希表与哈希冲突的解决(一)
  12. Unity TextMeshPro 制作字体用简体中文字符集 (仅用于开发)
  13. 移动硬盘安装Linux后无引导,移动固态硬盘安装Ubuntu启动盘后按F12根本就没有该系统启动项...
  14. android bugly 错误分析,# app 3.6.1 Bugly中崩溃分析
  15. xpadder教程:自定义设置游戏手柄的图片
  16. VBA之FormulaR1C1属性
  17. 怎么知道网站是否被黑 服务器是否被入侵呢
  18. 【持续更新中······】 各种模板+神奇黑科技
  19. 软件四种维护详解(更正性维护、适应性维护、完善性维护、预防性维护)
  20. 失落的时候如何调整自己的心情

热门文章

  1. PLSQL 的中文乱码解决方法(简单实用)
  2. 无需上架,接入穿山甲广告和广点通广告 sdk
  3. Crowd Control
  4. C语言学习笔记 |进阶| 内存函数
  5. 关于word和excel实现套打快递单的问题
  6. 中国大学MOOC课程《Python语言程序设计》课后练习第一周
  7. 不改恶习,是否可往净土
  8. P1786 帮贡排序
  9. 传智健康day05 预约管理-预约设置
  10. 二十一世家赚钱之门路-----小投资大生意