




已阅读5页,还剩17页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Reference TablesPython KeywordsTable B.1 lists Pythons keywords.Table B.1 Python KeywordsaandasbassertcbreakclasscontinuedefdelelifelseexceptexecfinallyforfromglobalifimportinislambdanotorpassprintraisereturntrywhilewithbyielddNoneea.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 FunctionsPython标准操作符与函数Table B.2 represents the operators and (built-in and factory) functions that can be used with most standard Python objects as well as user-defined objects in which you have implemented their corresponding special methods.Table B.2 Standard Type Operators and FunctionsOperator/functionDescriptionResultaString representationEvaluatable string representationstrBuilt-in and factory functionscmp(obj1, obj2)Compares two objectsintrepr(obj)Evaluatable string representationstrstr(obj)Printable string representationstrtype(obj)Object typetypeTable B.2 Standard Type Operators and Functions (continued)operator/functionDescriptionResultaValue comparisonsGreater thanbool=Greater than or equal tobool=Equal tobool!=Not equal toboolNot equal toboolObject comparisonsisThe same asboolis notNot the same asboolBoolean operatorsnotLogical negationboolandLogical conjunctionboolorLogical disjunctionboola.Boolean comparisons return either True or False.Numeric Type Operators and Functions数字类型操作符与函数Table B.3 represents the operators and (built-in and factory) functions that apply to Pythons numeric objects.Table B.3 Operators and Built-in Functions for All Numeric TypesOperator/built-inDescriptionintlongfloatcomplexResultaabs()Absolute valuenumberachr()Characterstr(continued )Table B.3 Operators and Built-in Functions for All Numeric Types(continued)Operator/built-inDescriptionintlongfloatcomplexResultacoerce()Numeric coerciontuplecomplex()Complex factorycomplexfunctiondivmod()Division/modulotuplefloat()Float factory functionfloathex()Hexadecimal stringstrint()Int factory functionintlong()Long factory functionlongoct()Octal stringstrord()Ordinal(string)intExponentiationnumberFloat roundingfloatExponentiationnumberNo changenumberNegationnumberBit inversionint/longpow()round()*b+c-cc*bExponentiationnumber*Multiplicationnumber/Classic or true divisionnumber/Floor divisionnumber%Modulo/remaindernumberTable B.3 Operators and Built-in Functions for All Numeric Types(continued)Operator/built-inDescriptionintlongfloatcomplexResulta+Additionnumber-SubtractionnumberBit right shiftint/long&Bitwise ANDint/longBitwise XORint/long|Bitwise ORint/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序列类型操作符与函数Table B.4 contains the set of operators, (built-in and factory) functions, and built-in methods that can be used with sequence types.Table B.4 Sequence Type Operators, Built-in Functions, and MethodsOperator, built-infunction or methodstrlisttuple (list creation)()“append()(continued )Table B.4 Sequence Type Operators, Built-in Functions, and Methods(continued)Operator, built-infunction or methodstrlisttuplecapitalize()center()chr()cmp()count()decode()encode()endswith()expandtabs()extend()find()hex()index()insert()isdecimal()isdigit()islower()isnumeric()isspace()istitle()isupper()join()Table B.4 Sequence Type Operators, Built-in Functions, and Methods(continued)Operator, built-infunction or methodstrlisttuplelen()list()ljust()lower()lstrip()max()min()oct()ord()pop()raw_input()remove()replace()repr()reverse()rfind()rindex()rjust()rstrip()sort()split()(continued )Table B.4 Sequence Type Operators, Built-in Functions, and Methods(continued)Operator, built-infunction or methodstrlisttuplesplitlines()startswith()str()strip()swapcase()split()title()tuple()type()upper()zfill(). (attributes) (slice):*%+innot inString Format Operator Conversion Symbols字符串格式操作符转换符号Table B.5 lists the formatting symbols that can be used with the string format operator ( % ).String Format Operator Directives字符串格式操作符命令When using the string format operator (see Table B.5), you may enhance or fine-tune the object display with the directives shown in Table B.6.Table B.5 String Format Operator Conversion SymbolsFormat SymbolConversion%cCharacter (integer ASCII value or string of length 1)%raString conversion via repr() prior to formatting%sString conversion via str() prior to formatting%d/ %iSigned decimal integer%ubUnsigned decimal integer%ob(Unsigned) octal integer%xb / %Xb(Unsigned) hexadecimal integer (lower/UPPERcase letters)%e / %EExponential notation (with lowercase e/UPPERcase E)%f / %FFloating point real number (fraction truncates naturally)%g/ %GThe 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 DirectivesSymbolFunctionality*Argument specifies width or precision-Use left justification+Use a plus sign ( + ) for positive numbersUse space-padding for positive numbers#Add the octal leading zero (0) or hexadecimal leading 0xor 0X, depending on whether x or X were used0Use zero-padding (instead of spaces) when formatting numbers% leaves you with a single literal %(var)Mapping variable (dictionary arguments)m.nm is the minimum total width and n is the number of digits to display after the decimal point (if applicable)String Type Built-in Methods字符穿类型内建函数The descriptions for the string built-in methods listed above are given inTable B.7.Table B.7 String Type Built-in MethodsMethod NameDescriptionstring.capitalize()Capitalizes first letter of string string.center(width)Returns a space-padded string withthe original string centered to a totalof width columnsstring.count(str, beg=0,end=len(string)Counts how many times str occurs in string, or in a substring of string if starting index beg and ending indexend are givenTable B.7 String Type Built-in Methods (continued)Method NameDescriptionstring.decode(encoding=UTF-8, errors=strict) * ed. add FN: New in Python 2.2string.encode(encoding=UTF-8, errors=strict)astring.endswith(str, beg=0,end=len(string)bReturns decoded string version of string; on error, default is to raise a ValueEr- ror unless errors is given withignore or replaceReturns encoded string version of string; on error, default is to raise a ValueEr- ror unless errors is given withignore or replaceDetermines 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=0end=len(string)string.index(str, beg=0,end=len(string)Determines if str occurs in string, or in a substring of string if starting index beg and ending index end are given; returns index if found and -1 otherwiseSame as find(), but raises an excep- tion if str not foundstring.isalnum()a,b,cReturns True if string has at least 1 character and all characters are alphanu- meric and False otherwisestring.isalpha()a,b,cReturns True if string has at least 1 character and all characters are alpha- betic and False otherwisestring.isdecimal()b,c,dReturns True if string contains only decimal digits and False otherwisestring.isdigit()b,cReturns True if string contains only digits and False otherwisestring.islower()b,cReturns True if string has at least 1 cased character and all cased characters are in lowercase and False otherwise(continued )Table B.7 String Type Built-in Methods (continued)Method NameDescriptionstring.isnumeric()b,c,dReturns True if string contains only numeric characters and False otherwisestring.isspace()b,cReturns True if string containsonly whitespace characters and Falseotherwisestring.istitle()b,cReturns True if string is properly“titlecased” (see title() and Falseotherwisestring.isupper()b,cReturns True if string has at least one cased character and all casedcharacters are in uppercase and Falseotherwisestring.join(seq)Merges (concatenates) the string repre- sentations of elements in sequence seq into a string, with separator stringstring.ljust(width)Returns a space-padded string with the original string left-justified to a totalof width columnsstring.lower()Converts all uppercase letters instring to lowercasestring.lstrip()Removes all leading whitespace instringstring.replace(str1, str2, num=string.count(str1)string.rfind(str, beg=0,end=len(string)string.rindex( str, beg=0,end=len(string)Replaces all occurrences of str1 in string with str2, or at most num occurrences if num givenSame as find(), but search backwards in stringSame as index(), but search back- wards in stringstring.rjust(width)Returns a space-padded string with the original string right-justified to a total of width columnsTable B.7 String Type Built-in Methods (continued)Method NameDescriptionstring.rstrip()Removes all trailing whitespace ofstringstring.split(str=, num=string.count(str)string.splitlines(num=string.count(n)b,cstring.startswith(str, beg=0,end=len(string)bSplits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if givenSplits string at all (or num) NEW- LINEs and returns a list of each line with NEWLINEs removedDetermines if string or a substring of string (if starting index beg and end- ing index end are given) starts with sub- string str; returns True if so, and False otherwisestring.strip(obj)Performs both lstrip() andrstrip() on stringstring.swapcase()Inverts case for all letters in string string.title()b,cReturns “titlecased” version of string,that is, all words begin with uppercase,and the rest are lowercase (also seeistitle()string.translate(str, del=) Translates string according to transla- tion table str (256 chars), removingthose 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 charac- ters; 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 MethodsList类型内方法In Table B.8, we present full descriptions and usage syntax for the list built-in methods given above.Dictionary Type Built-in MethodsDictionary类型内建方法In Table B.9, we list the full description and usage syntax for the dictionary built-in methods listed below.Table B.8 List Type Built-in MethodsList MethodOperationlist.append(obj)Adds obj to the end of list list.count(obj)Returns count of how many times obj occursin listlist.extend(seq)alist.index(obj, i=0, j=len(list)Appends contents of seq to listReturns lowest index k where listk = obj and i = k j; otherwise ValueError raisedlist.insert(index, obj)Inserts obj into list at offset index list.pop(index=-1)aRemoves and returns obj at given or lastindex from listlist.remove(obj)Removes object obj from list list.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.Table B.9 Dictionary Type MethodsMethod NameOperationdict.cleara()Removes all elements of dict dict.copya()Returns a (shallowb) copy of dictdict.fromkeysc(seq,val=None)dict.get(key,default=None)aCreates and returns a new dictionary with the ele- ments of seq as the keys and val as the initial value (defaults to None if not given) for all keysFor 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 opera- tors in 2.2 but still provides a functional interfacedict.items()Returns a list of the (key, value) tuple pairs of dict dict.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)dict.setde- fault(key, default=None)eSimilar to get() but removes and returnsdictkey if key present and raises KeyErrorif key not in dict and default not givenSimilar to get(), but sets dictkey=defaultif key is not already in dictdict.update(dict2)aAdds the key-value pairs of dict2 to dict dict.values()Returns a list of the values of dicta.New in Python 1.5b.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 FunctionsSet类型操作符与函数Table B.10 outlines the various operators, (built-in and factory) functions, and built-in methods that apply to both set types (set mutable and froz- enset immutable).Table B.10 Set Type Operators, Functions, and MethodsFunction/MethodNameOperatorEquivalent DescriptionAll Set Typeslen(s)Set cardinality: number of elements in s set(obj)Mutable set factory function; if obj given, itmust be iterable, new set elements taken fromobj; 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 sNon-membership test: is obj not an element of s?s = tEquality test: do s and t have exactly the same elements?s != tInequality test: opposite of =s t(Strict) subset test; s != t and all elements ofs are members of ts.issubset(t)s t(Strict) superset test: s != t and all elements of t are members of ss.issuper- set(t)s = tSuperset test (allows improper supersets): all elements of t are members of sTable B.10 Set Type Operators, Functions, and Methods (continued)Function/MethodNameOperatorEquivalent DescriptionAll Set Typess.union(t)s | tUnion operation: elements in s or ersec- tion(t)s.differ- ence(t)s.symmetric_di fference(t)s & tIntersection operation: elements in s and ts - tDifference operation: elements in s that are not elements of ts tSymmetric 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 tadded to ersection_update(t)s.difference_u pdate(t)s.symmetric_ difference_up- date(t)s &= tIntersection update operation: s only contains members of the original s and ts -= tDifference update operation: s only contains original members who are not in ts = tSymmetric difference update operation: sonly 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
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 外包加工制造业务合作协议的详细规定说明
- 自然地理奇葩题目及答案
- 农民与社区小区农业种植协议
- 专家经验面试题目及答案
- 创新创意孵化过程模板团队拓展支持
- 写人作文我的同学800字(11篇)
- 2025年刮墨刀合作协议书
- 存梦银行课件
- 化工厂安全学习培训课件
- 2025汽车销售合同样本
- 水利工程建设项目安全生产 风险管控“六项机制”建设标准
- 2025-2026学年北师大版数学小学三年级上册(全册)教案设计及教学计划
- 2025年部编版新教材道德与法治二年级上册教学计划(含进度表)
- 2025年秋八年级开学主题班会第一课课件(初二正青春拼搏向暖阳)
- 2025秋人教版(2024)八年级上册地理 【教学课件】1.1.1 《疆域》
- GB/T 45355-2025无压埋地排污、排水用聚乙烯(PE)管道系统
- 四级育婴员模拟考试题及答案
- 绍兴文理学院基建处工程管理人员的工作职责管理制度及考核办法
- 公路施工组织设计 网络计划技术
- 详解农村死人后的习俗
- 第三章无人机结构PPT课件
评论
0/150
提交评论