Python简明手册(新).doc_第1页
Python简明手册(新).doc_第2页
Python简明手册(新).doc_第3页
Python简明手册(新).doc_第4页
Python简明手册(新).doc_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Python KeywordsTable B.1 lists Pythons keywords.Table B.1. Python KeywordsaAnd asb assertc break class continue def del elif else except exec finally for from globalif import in is lambda not or pass print raise return Try while withb yieldd Noneea access keyword obsoleted in Python 1.4. b New in Python 2.6. c New in Python 1.5. d New in Python 2.3. e Not a keyword but made a constant in Python 2.4.Python Standard Operators and FunctionsTable B.2. Standard Type Operators and FunctionsOperator/function DescriptionString representation Evaluatable string representation str Built-in and factory functionscmp(obj1, obj2) Compares two objects intrepr(obj) Evaluatable string representation strstr(obj) Printable string representation strtype(obj) Object type type Value comparisons Greater than bool= Greater than or equal to bool= Equal to bool!= Not equal to bool Not equal to boolObject comparisonsis The same as boolis not Not the same as boolBoolean operatorsnot Logical negation booland Logical conjunction boolor Logical disjunction bool - a Boolean comparisons return either true or False.Numeric Type Operators and FunctionsTable B.3. Operators and Built-in Functions for All Numeric TypesOperator/built-in Description int long float complexabs() Absolute value numberachr() Character strcoerce() Numeric coercion tuplecomplex() Complex factory function complexdivmod() Division/modulo tuplefloat() Float factory function floathex() Hexadecimal string strint() Int factory function intlong() Long factory function longoct() Octal string strord() Ordinal (string) intpow() Exponentiation numberround() Float rounding float*b Exponentiation number+c No change number-c Negation numberc Bit inversion int/long*b Exponentiation number* Multiplication number/ Classic or true division number/ Floor division number% Modulo/remainder number+ Addition number- Subtraction number Bit right shift int/long& Bitwise AND int/long Bitwise XOR int/long| Bitwise OR int/longa A result of number indicates any of the numeric types, perhaps the same as the operands.b * has a unique relationship with unary operators; see Section 5.5.3 and Table 5.2. c Unary operator.Sequence Type Operators and Functions (list creation) () append() capitalize() center() chr() cmp() count() decode() encode() endswith() expandtabs() extend() find() hex() index() insert() isdecimal() isdigit() islower() isnumeric() isspace() istitle() isupper() join() len() list() ljust() lower() lstrip() max() min() oct() ord() pop() raw_input() remove() replace() repr() reverse() rfind() rindex() rjust() rstrip() sort() split() splitlines() startswith() str() strip() swapcase() split() title() tuple() type() upper() zfill() . (attributes) (slice) : * % + in not in String Format Operator Conversion SymbolsString Format Operator DirectivesTable B.5. String Format Operator Conversion SymbolsFormat Symbol Conversion%c Character (integer ASCII value or string of length 1)%ra String conversion via repr() prior to formatting%s String conversion via str() prior to formatting%d / %i Signed decimal integer%ub Unsigned decimal integer%ob (Unsigned) octal integer%xb/ %Xb (Unsigned) hexadecimal integer (lower/UPPERcase letters)%e / %E Exponential notation (with lowercase e/UPPERcase E)%f / %F Floating point real number (fraction truncates naturally)%g / %G The shorter of %e and %f/%E% and %F% Percent character ( % ) unescapeda New in Python 2.0; likely unique only to Python. b %u/%o/%x/%X of negative int will return a signed string in Python 2.4+.Table B.6. Format Operator Auxiliary DirectivesSymbol Functionality* Argument specifies width or precision- Use left justification+ Use a plus sign ( + ) for positive numbers Use space-padding for positive numbers# Add the octal leading zero (0) or hexadecimal leading 0x or 0X, depending on whether x or X were used0 Use zero-padding (instead of spaces) when formatting numbers% % leaves you with a single literal %(var) Mapping variable (dictionary arguments)m.n m is the minimum total width and n is the number of digits to display after the decimal point (if applicable)String Type Built-in MethodsTable B.7. String Type Built-in Methods (continued)Method Name Descriptionstring.capitalize() Capitalizes first letter of stringstring.center(width) Returns a space-padded string with the originalstring centered to a total of width columnsstring.count(str, beg=0, end=len(string) Counts how many times str occurs in string, orin a substring of string if starting index beg and ending index end are givenstring.decode(encoding=UTF-8, errors=strict)* ed. add FN: New in Python 2.2Returns decoded string version of string; on error, default is to raise a ValueError unlesserrors is given with ignore or replacestring.encode(encoding=UTF-8, errors=strict)aReturns encoded string version of string; on error, default is to raise a ValueError unlesserrors is given with ignore or replacestring.endswith(str, beg=0, end=len(string)b Determines if string or a substring of string (if starting index beg and ending index end are given) ends with str; returns true if so, and False otherwisestring.expandtabs(tabsize=8) Expands tabs in string to multiple spaces;defaults to 8 spaces per tab if tabsize not providedstring.find(str, beg=0 end=len(string) Determines if str occurs in string, or in asubstring of string if starting index beg and ending index end are given; returns index iffound and -1 otherwisestring.index(str, beg=0, end=len(string) Same as find(), but raises an exception if str not foundstring.isalnum()a,b,c Returns true if string has at least 1 character and all characters are alphanumeric and False otherwisestring.isalpha()a,b,c Returns TRue if string has at least 1 character and all characters are alphabetic and False otherwisestring.isdecimal()b,c,d Returns TRue if string contains only decimal digits and False otherwisestring.isdigit()b,c Returns true if string contains only digits and False otherwisestring.islower()b,c Returns true if string has at least 1 casedcharacter and all cased characters are in lowercase and False otherwisestring.isnumeric()b,cd Returns true if string contains only numeric characters and False otherwisestring.isspace()b,c Returns true if string contains only whitespacecharacters and False otherwisestring.istitle()b,c Returns true if string is properlytitlecased (see title() and False otherwisestring.isupper()b,c Returns TRue if string has at least one casedcharacter and all cased characters are in uppercase and False otherwisestring.join(seq) Merges (concatenates) the string representations of elements in sequence seq intoa string, with separator stringstring.ljust(width) Returns a space-padded string with the original string left-justified to a total of width columnsstring.lower() Converts all uppercase letters in string to lowercasestring.lstrip() Removes all leading whitespace in stringstring.replace(str1, str2, num=string.count(str1)Replaces all occurrences of str1 in string with str2, or at most num occurrences if num givenstring.rfind(str, beg=0, end=len(string) Same as find(), but search backwards in stringstring.rindex(str, beg=0, end=len(string) Same as index(), but search backwards in stringstring.rjust(width) Returns a space-padded string with the original string right-justified to a total of width columnsstring.rstrip() Removes all trailing whitespace of stringstring.split(str=, num=string.count(str) Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if givenstring.splitlines(num=string.count(n)b,c Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removedstring.startswith(str, beg=0, end=len(string)bDetermines if string or a substring of string (ifstarting index beg and ending index end are given) starts with substring str; returns TRue if so, and False otherwisestring.strip(obj) Performs both lstrip() and rstrip() on stringstring.swapcase() Inverts case for all letters in stringstring.title()b,c Returns titlecased version of string, that is, all words begin with uppercase, and the rest are lowercase (also see istitle()string.TRanslate(str, del= ) Translates string according to translation tablestr (256 chars), removing those in the del stringstring.upper() Converts lowercase letters in string to uppercasestring.zfill(width) Returns original string left-padded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero)a Applicable to Unicode strings only in 1.6, but to all string types in 2.0. b Not available as a string module function in 1.5.2.c New in Python 2.1. d Applicable to Unicode strings only.List Type Built-in MethodsTable B.8. List Type Built-in MethodsList Method Operationlist.append(obj) Adds obj to the end of listlist.count(obj) Returns count of how many times obj occurs in listlist.extend(seq)a Appends contents of seq to listlist.index(obj, i=0, j=len(list) Returns lowest index k where listk = obj and i = k j; otherwise ValueError raisedlist.insert(index, obj) Inserts obj into list at offset indexlist.pop(index=-1)a Removes and returns obj at given or last index from listlist.remove(obj) Removes object obj from listlist.reverse() Reverses objects of list in placelist.sort(func=None, key=None, reverse=False) Sorts list members with optional comparison function; key is a callback when extracting elements for sorting, and if reverse flag is true, then list is sorted in reverse ordera New in Python 1.5.2.Dictionary Type Built-in MethodsTable B.9. Dictionary Type MethodsMethod Name Operationdict.cleara()Removes all elements of dictdict.copya() Returns a (shallowb) copy of dictdict.fromkeysc(seq, val=None)Creates and returns a new dictionary with the elements of seq as the keys and val as the initial value (defaults to None if not given) for all keysdict.get(key, default=None)a For key key, returns value or default if key not in dict (note that defaults default is None)dict.has_key(key) Returns true if key is in dict, False otherwise; partially deprecated by the in and not in operators in 2.2 but still provides a functional interfacedict.items() Returns a list of the (key, value) tuple pairs of dictdict.keys() Returns a list of the keys of dictdict.iter*d() iteritems(), iterkeys(), itervalues() are all methods that behave the same as their non-iterator counterparts but return an iterator instead of a listdict.popc(key, default)Similar to get() but removes and returns dictkey if key present and raises KeyError if key not in dict and default not givendict.setdefault(key, default=None)e Similar to get(), but sets dictkey=default if key is notalready in dictdict.update(dict2)a Adds the key-value pairs of dict2 to dictdict.values() Returns a list of the values of dicta New in Python 1.5 b More information regarding shallow and deep copies can be found in Section 6.19.c New in Python 2.3.d New in Python 2.2.e New in Python 2.0.Set Types Operators and FunctionsTable B.10. Set Type Operators, Functions, and MethodsFunction/Method Name Operator Equivalent Description All Set Typeslen(s) Set cardinality: number of elements in sset(obj) Mutable set factory function; if obj given,it must be iterable, new set elements taken from obj; if not, creates an empty setfrozenset (obj) Immutable set factory function; operates the same as set() except returns immutable setobj in s Membership test: is obj an element of s?obj not in s Non-membership test: is obj not an element of s?s = t Equality test: do s and t have exactly the same elements?s != t Inequality test: opposite of =s t (Strict) subset test; s !=t and all elements of s are members of ts.issubset(t) s t (Strict) superset test: s != t and all elements of t are members of ss.issuperset(t) s = t Superset test (allows improper supersets):all elements of t are members of ss.union(t) s | t Union operation: elements in s or ersection(t) s & t Intersection operation: elements in s and ts.difference(t) s - t Difference operation: elements in s that are not elements of ts.symmetric_difference(t) s t Symmetric difference operation: elements of either s or t but not boths.copy() Copy operation: return (shallow) copy of sMutable Sets Onlys.update(t) s |= t (Union) update operation: members of t added to ersection_update(t) s &= t Intersection update operation: s only contains members of the original s and ts.difference_update(t) s -= t Difference update operation: s only contains original members who are not in ts.symmetric_difference_update(t) s = t Symmetric difference update operation: s only contains members of s or t but not boths.add(obj) Add operation: add obj to ss.remove(obj) Remove operation: remove obj from s; Key-Error raised if obj not in ss.discard(obj) Discard operation: friendlier version of remove()remove obj from s if obj in ss.pop() Pop operation: remove and return an arbitrary element of ss.clear() Clear operation: remove all elements of sFile Object Methods and Data AttriobutesTable B.11. Methods for File ObjectsFile Object Attribute Descriptionfile.close() Closes filefile.fileno() Returns integer file descriptor (FD) for filefile.flush() Flushes internal buffer for filefile.isatty() Returns true if file is a tty-like device and False otherwisefile.nexta()Returns the next line in the file similar to file.readline() or raises Stop Iteration if no more lines are availablefile.read(size=-1) Reads size bytes of file, or all remaining bytes if size not given or is negative, as a string and return itfile.readintob(buf, size)Reads size bytes from file into buffer buf (unsupported)file.readline(size=-1) Reads and returns one line from file (includes line-ending characters), either one full line or a maximum of size charactersfile.readlines(sizhint=0) Reads and returns all lines from file as a list (includes all line termination characters); if sizhint given and 0, whole lines are returned consisting of approximately sizhint bytes (could be rounded up to next buffers worth)file.xreadlinesc()Meant for iteration, returns lines in file read as chunks in a more efficient way than readlines() file.seek(off, whence=0) Moves to a location within file, off bytes offset from whence (0 = beginning of file, 1 = current location, or 2 = end of file)file.tell() Returns current location within filefile.truncate(size=file.tell() Truncates file to at most size bytes, the default being the currentfile locationfile.write(str) Writes string str to filefile.writelines(seq) Writes seq of strings to file; seq should be an iterable producing strings; prior to 2.2, it was just a list of stringsfile.closed true if file is closed and False otherwisefile.encodingd Encoding that this file useswhen Unicode strings are written to file, they will be converted to byte strings using file.encoding; a value of None indicates that the system default encoding for converting Unicode strings should be usedfile.mode Access mode with which file was Name of filefile.newlinesd None if no line separators have been read, a string consisting of one type of line separator, or a tuple containing all types of line termination characters read so farfile.softspace 0 if space explicitly required with print, 1 otherwise; rarely used by the programmergenerally for internal use onlya New in Python 2.2. b New in Python 1.5.2 but unsupported. c New in Python 2.1 but deprecated in Python 2.3. d New in Python 2.3.Python ExceptionsTable B.12. Python Built-In ExceptionsException Name DescriptionBaseExceptiona Root class for all exceptions SystemExitb Request termination of Python interpreterKeyboardInterruptc User interrupted execution (usually by typing C)Exceptiond Root class for regular exceptionsStopIteratione Iteration has no further valuesGeneratorExita Exception sent to generator to tell it to quitSystemExitf Request termination of Python interpreterStandardErrord Base class for all standard built-in exceptionsArithmeticErrord Base class for all numeric calculation errorsFloatingPointErrord Error in floating point calculationOverflowError Calculation exceeded maximum limit for numerical typeZeroDivisionError Division (or modulus) by zero error (all numeric types)AssertionErrord Failure of assert statementAttributeError No such object attributeEOFError End-of-file marker reached without input from built-inEnvironmentError Base class for operating system environment errorsIOError Failure of input/output operationOSError Operating system errorWindowsError MS Windows system call failureImportError Failure to import mod

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论