Xem mẫu

58 Chapter 3 Table 3.4 Conversion Built-in Functions for Numeric Types FUNCTION int(ob) long(ob) float(ob) DESCRIPTION Converts a string or number object to an integer. Converts a string or number object to long. Converts a string or number object to a floating-point number. EXAMPLE >>>int(`15`) 15 >>>long(`12`) 12L >>> float(10) 10.0 complex(string) or complex(real,imag) Converts a string to >>> complex(`76`) a complex number (76+0j) or takes a real >>> complex(45,8) number and an (45+8j) imaginary number (optional) and returns a complex number with those components. Python also provides a few operational functions for numeric data types. Table 3.5 lists the operational functions applicable for numeric types. Table 3.5 Operational Functions for Numeric Types FUNCTION abs(ob) DESCRIPTION Converts the string or number object to its absolute. EXAMPLE >>> abs(-13) 13 >>> abs(5.) coerce(ob1,ob2) Converts ob1 and ob2 to the same numeric type and returns the two numbers as a tuple. 5.0 >>> coerce(12.0,8) (12.0, 8.0) >>> coerce(2,86L) (2L, 86L) TEAM LinG - Live, Informative, Non-cost and Genuine! Intrinsic Operations and Input/Output 59 FUNCTION divmod(ob1,ob2) DESCRIPTION Divides ob1 and ob2 and returns both the quotient and remainder as a tuple. For complex numbers, the quotient is rounded off. Complex numbers use only the real component of the quotient. EXAMPLE >>> divmod(10,6) (1, 4) >>> divmod(10.6,3.4) (3.0, 0.39999999999999991) >>> divmod(78,23l) pow(ob1,ob2,mod) Raises ob2 to the power of ob1. Takes an optional argument mod, divides the result by mod, and returns the remainder. (3L, 9L) >>> pow(2,3) 8 >>> pow(2,3,5) 3 round(flt,dig) Rounds off the float flt to the dig digits after the decimal point and assumes 0 if dig is not supplied. >>> round(67.5324) 68.0 >>> round(4.46,1) 4.5 In addition to the built-in functions that are applicable for all numeric types, Python has some functions applicable only to integers. These functions can be classified into base and ASCII conversion functions. You already know that Python supports the hexadecimal and octal representation of numbers. You can use the base conversion functions to convert an integer into its hexa-decimal or octal equivalent. These functions are hex() and oct(). Both functions take an integer and return a corresponding hexadecimal or octal equivalent as a string. >>> hex(35) ‘0x23’ >>> hex(677) ‘0x2a5’ >>> hex(4*789) ‘0xc54’ >>> hex(45L) ‘0x2DL’ >>> oct(863) ‘01537’ >>> oct(6253915L) ‘027666533L’ TEAM LinG - Live, Informative, Non-cost and Genuine! 60 Chapter 3 Python also provides functions to convert integers into their ASCII (American Stan-dard for Information Interchange) characters and vice versa. Each character is mapped to a unique numeric value from 0 to 255, listed in a table called the ASCII table. The mapping remains the same for all machines using the ASCII table. The ord() function takes a single character and returns the ordinal value associated with that ASCII char-acter. For example, >>> ord(‘d’) 100 >>> ord(‘D’) 68 >>> ord(‘l’) 108 To convert a value to its corresponding ASCII character, you can use the chr() function. For example, >>> chr(65) ‘A’ >>> chr(100) ‘d’ >>> chr(108) ‘l’ You saw how intrinsic operations on integers make it simple to handle program-ming tasks for which you might have to write long code. Let’s learn some intrinsic operations possible for strings. Intrinsic Operations for Strings We discussed the cmp(), max(), and min() standard type functions, which perform lexicographic comparison for all types. We also discussed the len() sequence type function, which returns the length of a sequence. In addition, the max() and min() functions can be used to find the character with the minimum and maximum values, respectively. For example, >>> max(‘abc’) ‘c’ >>> min(‘abc’) ‘a’ Often, you might need to convert a value of a particular data type into a string. Python allows you to do this in a number of ways. The repr() function. You can pass an object of any data type to the repr() function to convert it to a string. >>> astr=repr(76) >>> astr ‘76’ TEAM LinG - Live, Informative, Non-cost and Genuine! Intrinsic Operations and Input/Output 61 Recall that the presence of double or single quotes indicates that astr is a string. >>> ls=[43,12.23] >>> bstr=repr(ls) >>> bstr ‘[43, 12.23]’ >>>cstr=’xyz’ >>> ls=[astr,cstr] >>> ls_str=repr(ls) >>> ls_str “[‘76’, ‘xyz’]” The str() function. You can also pass the value to the str() function. For example, >>> a=’Flower \tred’ >>> b=78 >>> tup=(a,b) >>> str(tup) “(‘Flower \\tred’, 78)” Note that using the str() function to convert to a string adds backslashes if a backslash is already present. This happens regardless of the method you use to convert to a string. >>> print str(tup) (‘Flower \tred’, 78) As expected, the escape character and the backslash appear in the string when displayed using with the print statement and is not replaced with the corre-sponding special character, which is a horizontal tab in this case. Reverse quotes (` `). You can write the value or variable in reverse quotes to convert it to a string. This method works for all data types except numbers. >>> tup=(‘rep’,’tree’) >>> `tup` “(‘rep’, ‘tree’)” >>> jo=’welcome’ >>> string=`jo` >>> string “‘welcome’” Note that when you enclose a string within reverse quotes, string quotes are added to it. >>> `5*30` ‘150’ If the value enclosed in the reverse quotes is an expression, it is evaluated first and then converted into a string. In addition to the functions discussed previously, Python also provides some com-mon operations for strings in the form of methods. For example, the capitalize() method capitalizes the first character of a string. These methods can be called using a variable containing a string value. TEAM LinG - Live, Informative, Non-cost and Genuine! 62 Chapter 3 >>> s=’hello’ >>> s.capitalize() ‘Hello’ Table 3.6 lists some of these methods for strings. Table 3.6 String Type Built-in Methods METHOD s.capitalize() s.center(width) s.count((sub[, start[, end]]) s.endswith(sub[, start[, end]]) s.expandtabs([tabsize]) s.find(sub[, start[, end]]) s.index(sub[, start[, end]]) EXPLANATION Capitalizes the first letter of the string s. Centers the string in the length specified by width and pads the columns to the left and the right with spaces. Counts the number of occurrences of sub in the string s beginning from the start index and continuing until the end index. Both start and end indices are optional and default to 0 and len(s), respectively, if not supplied. Returns 1 if the string s ends with the specified substring sub; otherwise returns -1. Search begins from the index start until the end of the string. Default is to start from the beginning and finish at the end of the string. Returns the string after replacing all tab characters with spaces. If tabsize is not given, the tab size defaults to 8 characters. Returns the beginning index in the string where the substring sub begins from the start index and continues until the end index. Both start and end indices are optional and default to 0 and len(s) if not supplied. Similar to find() but raises an exception if the string is not found. TEAM LinG - Live, Informative, Non-cost and Genuine! ... - tailieumienphi.vn