The [Python] operator and an expression

Source: Internet
Author: User
Tags bitwise chr floor division logical operators ord pow

1. Digital operation

All numeric types can do the following:

Operation Description
X + y Addition
X-y Subtraction
X * y Multiplication
X/Y Division
X//Y Truncate DIVISION
X * * y Powers (Y-squares of X)
X% y modulo (x mod y)
-X One-dollar subtraction
+x One-dollar addition

The Truncation division operator "//", also known as floor division, intercepts the result as an integer, and both integers and floating-point numbers can be applied. The modulo operator returns the remainder of x//Y, and for floating-point numbers, the modulo operator returns the floating-point remainder of x//Y. For complex numbers, the modulo and truncate division operators are not valid.
The following shift and bitwise logical operators can only be applied to integers:

Operation Description
X << y Move left
X >> y Move right
X & Y Bitwise-AND
x | Y Bitwise OR
x ^ y Bitwise XOR OR
~x Bitwise negation

The following built-in functions support all numeric types:

Operation Description
ABS (x) Absolute
Divmod (x, y) return (x//y, x% y)
Pow (x, y [, modulo]) Return (x * * y)% module
Round (x [, N]) Rounded to a multiple of close 10^-n (returns only floating-point numbers)

The ABS () function returns the absolute value of the number. The Divmod () function returns the quotient and remainder of the division operation and is valid only for non-complex numbers. The POW () function can be used instead of the * * operator. The round () function rounds a floating-point number x to a multiple of the nearest 10^-n, and if n is omitted, it is set to 0.
The following comparison operators have a standard mathematical interpretation, and the return value is true or False for a Boolean type:

Operation Description
X < y Less than
X > Y Greater than
x = = y Equals
X! = y Not equal to
X >= y Greater than or equal
X <= y Less than or equal

Comparison operators can be linked together, such as x < Y < Z. This type of expression is equivalent to x < Y and y < Z. The complex number is not allowed to be compared, or a TypeError exception is thrown. Operations on these operands are valid only if the operands are of the same type. For built-in numbers, Python enforces type conversions, with the following conversion rules:
1) If one of the operands is a complex number, the other operand is also converted to a complex number.
2) If one of the operands is a floating-point number, the other operand is also converted to a floating-point number.
3) Otherwise, the two operands must be integers and do not need to be converted.

2. Sequence operations

The supported operators for sequence types (including strings, lists, and tuples) are as follows:

variable unpacking Minimum item in Maximum items in
action description
s + R connection
s N, n s make n copies of S, n integers
v1, v2 ..., vn = s
s[i] index
s[i:j] slice
S[i:j:stride] Extended slices
x in S, x not in S dependency
for X in S: Iteration
All (s) returns False if all items in s are true
any (s) returns True if any of the entries in S are true
Len (s) length
min (s) s
max (s) s
sum (s [, initial]) items with optional initial values and

The "+" operator is used to connect two sequences of the same type. The S * n operator makes a sequence of n copies. However, these replicas are only shallow copies.
All sequences can be unpacked as a list of variable names, for example:

items = [3, 4, 5]x, y, z = itemsdatetime = ((5, 19, 2008), (10, 30, "am"))(month, day, year), (hour, minute, am_pm) = datetime

When you unpack a value into a variable, the number of variables must match exactly the number of elements in the sequence. In addition, the structure of the variable must match the structure of the sequence.
The index operator S[n] returns the Nth object in a sequence, while S[0] is the first object. Use a negative index to get the trailing character of the sequence. Attempting to access an element that is out of bounds throws an Indexerror exception.
The slice operator S[i:j] extracts a subsequence from S that contains the element index K range of I <= K < J. The slice operator supports using a negative index and assumes that it is associated to the end of the sequence.
The x in S operator tests whether the object x is in the sequence s, and the return value is true or false. Similarly, the x not in S operator tests whether x is in the sequence S. For string objects, the in and not-in operators accept substrings. For example: "' Hello ' in ' Hello World '." It is important to note that the in operator does not support wildcard characters or any class of pattern matching.
The for X in S operator is used to iterate over all elements of a sequence. Len (s) returns the number of elements in the sequence. Min (s) and Max (s) return the minimum and maximum values in a sequence, respectively. SUM (s) is used to sum all the items in S, but only when each of them represents a number.
Strings and tuples are immutable and cannot be modified after they are created. The list can be modified by the following operators:

Operation Description
S[i] = X Index Assignment
S[I:J] = R Slice Assignment
S[i:j:stride] = R Slice extension Assignment
Del S[i] Delete an element
Del S[i:j] Delete a slice
Del S[i:j:stride] Delete an extended slice

S[i] = x operator modifies the list's element I to reference object x, increasing the reference count of X. A negative index value is associated to the end of the list, and an attempt to assign a value to an out-of-range index throws an Indexerror exception. The slice assignment operator s[i:j] = R replaces the element k with the element in sequence R, where the range of k is I <= K < J. If necessary, the sequence s is expanded or shrunk to accommodate all the elements in R, for example:

a = [1, 2, 3, 4, 5]a[1] = 6 # a = [1, 6, 3, 4, 5]a[2:4] = [10, 11] # a = [1, 6, 10, 11, 5]a[3:4] = [-1, -2, -3] # a = [1, 6, 10, -1, -2, -3, 5]a[2:] = [0] # a = [1, 6, 0]

The slice assignment can provide an optional stepping parameter. However, this behavior is more restrictive and the right argument must be exactly the same as the number of elements to replace the slice.
The Del s[i] operator removes the element i from the list while reducing its reference count. Del S[i:j] Deletes all elements within the slice. Slice deletion can also specify stepping parameters.
The sequence can be compared using operators <, >, <=, >=, = =,! =. When comparing two sequences, the first element of each sequence is compared first. If they are different, it is possible to draw a conclusion. If they are the same, continue to compare. If a is a sub-sequence of B, then a < b.

3. String formatting

The modulo operator (s% d) generates a formatted string where S is a format string, and D is an object tuple or mapping object (dictionary). The format string contains two types of objects: ordinary characters and conversion specifiers, which are replaced with a formatted string that can represent the relevant tuple or element in the map. If D is a tuple, the number of conversion specifiers must be consistent with the number of objects in D. If D is a map, each conversion specifier must be associated with a valid key name in the map. Each conversion specifier starts with a%, as in the following table:

character output format
D, I decimal integer or Long integer Number
u unsigned integer or long integer
o octal integer or Long integer
x hexadecimal integer or Long integer
x hexadecimal integer (capital letter)
F floating-point numbers, such as [-]m.dddddd
e Floating-point numbers, such as [-]m.dddddd+ (-) xx
e Floating-point numbers, such as [-]m.dddddd+ (-) XX
G, G exponent less than-4 or higher precision when using%e or%e, otherwise use%f
s string or arbitrary object
R strings generated with repr ()
C single character
% literal%

Between the% character and the converted character, the following modifiers can appear, and can only occur in the following order:
1) A key name in parentheses that is used to select a specific item from the mapping object.
2)-, left alignment flag. The default is right-justified.
3) +, indicates that the number symbol should be included.
4) 0, which represents a 0 padding.
5) A number specifying the minimum automatic width.
6) A decimal points for dividing the field width by precision.
7) A number that specifies the maximum number of characters to be printed in the string, the number of digits after the decimal point in the floating-point numbers, or the minimum number of digits of an integer.
The asterisk "*" character is used to replace a number in any field of any width.
The following code gives some examples:

a = 42b = 13.142783c = "hello"d = {‘x‘:13, ‘y‘:1.54321, ‘z‘: ‘world‘}e = 5628398123741234r = "a is %d" % a # r = "a is 42"r = "%10d %f" % (a, b) # r = "        42  13.142783"r = "%+010d %E" % (a, b) # r = "+0000000042 1.314278E+01"r = "%(x)-10d %(y)0.3g" % d # r = "13        1.54"r = "%0.4s %s" % (c, d[‘z‘]) # r = "hell world"r = "%*.*f" % (5, 3, b) # r = "13.143"r = "e = %d" % e # r = "e = 5628398123741234"

String formatting has a more advanced form, the S.format (args, Kwargs) method that uses strings. This method collects any collection of positional and keyword parameters and uses their values to replace the embedded placeholders in S. For example:

r = "{0} {1} {2}".format{‘GOOG‘, 100, 490.91}r = "{name} {shares} {price}".format{name=‘GOOG‘, shares=100, price=490.10}

If you want to output a "{" or "}", you must use the form "{{" or "}}". You can also use placeholders to perform other index and property lookups, such as:

stock = {    ‘name‘: ‘GOOG‘,    ‘shares‘: 100,    ‘price‘: 490.91}r = "{0[name]} {0[shares]} {0[price]}".format(stock)

Only names are allowed in these extensions, and no arbitrary expressions, method calls, and other operations are supported. Alternatively, you can specify the format specifier. The method is to add an optional format specifier to each placeholder with a colon ":", for example:

r = "{name:8} {shares:8d} {price:8.2f}".format(name=‘GOOG‘, shares=100, price=490.10)

The general format of specifiers is that each part of [fill[align]][sign][0][width][.pricision][type],[] is optional. The width specifier specifies the minimum field width to use, and the value of the align specifier is one of "<", ">", or "^", representing the left, right, and center alignment in the field, respectively. Fill is an optional fill character used to fill the blanks. The type descriptor represents the types of data. The sign portion of the format specifier is one of "+", "-" or "space", which represents the symbol. The precision portion of the specifiers is used to provide a precision position for the decimal number.

4. Dictionary and Collection operations

The dictionary provides a mapping between a name and an object, and it supports the following actions:

Operation Description
x = D[k] Index by key
D[K] = X Assigning by key
Del D[k] Delete an item by key
K in D To test whether a key exists
Len (d) Number of items in the dictionary

The value of the key can be any immutable object, such as a string, a number, and a tuple. In addition, the key of a dictionary can be a comma-separated value, for example:

d = {}d[1, 2, 3] = "foo"d[1, 0, 3] = "bar"# 等价于d[(1, 2, 3)] = "foo"d[(1, 0, 3)] = "bar"

The set and Frozenset types support a number of common collection operations, as follows:

Operation Description
s | T The set of S and T
S & T Intersection of S and T
S-t Finding the difference set
s ^ t Seeking symmetry Difference sets
Len (s) Number of items in the collection
Max (s) Maximum Value
Min (s) Minimum value

The result of the set, intersection, and difference operations is the same type as the leftmost operand. For example, if S is a frozenset and T is a set, then the type of the result will be frozenset.

5. Incremental assignment

The incremental assignment operators provided by Python are as follows:

Operation Description
x + = y x = x + y
X-= y x = XY
X *= y x = x * y
X/= y × = x/y
X//= y x = x//Y
X **= y x = x * * y
X%= y x = x% y
X &= y x = x & y
X |= y x = x | Y
X ^= y x = x ^ y
X >>= y x = x >> y
X <<= y x = x << y

Incremental assignments do not violate variability or modify objects in situ. Therefore, when you execute code x + = y, a new object x with a value of X + y is created.

6. Properties and Function call operators

Point "." Operator is used to access the properties of an object, such as

foo.x = 3print(foo.y)a = foo.bar(3, 4, 5)

Multiple point operators, such as FOO.Y.A.B, can appear in an expression. The point operator can also be used for intermediate results of a function, such as a = Foo.bar (3, 4, 5). Spam.
The f (args) operator is used to invoke a function on F. Each parameter of the function is an expression. All parameter expressions are evaluated from left to right before the function is called, which is sometimes referred to as an application-order evaluation. function parameters can be partially evaluated using the partial () function in the Functools module, for example:

def foo(x, y, z):    return x + y + zfrom functools import partialf = partial(foo, 1, 2) # 为foo的参数x和y提供值f(3) # 调用foo(1, 2, 3)

The partial () function evaluates some parameters of a function and returns an object that can be called later to provide the remaining arguments. The partial evaluation of function parameters is closely related to the process called the localization. The so-called mechanism of the process is to decompose a function with multiple parameters into a series of functions, each with one of the parameters.

7. Conversion functions

Sometimes you have to perform conversions between built-in types by simply using the type name as a function. In addition, there are several built-in functions that can be used to perform special class conversions. All of these functions return a new object that represents the converted value.

function Description
int (x [, Base]) Converts x to an integer. If x is a string, base is used to specify the cardinality
Float (x) Convert x to a floating-point number
Complex (real [, Imag]) Create a complex number
STR (x) Converts an object x to a string representation
REPR (x) Convert object x to an expression string
Format (x [, Format_spec]) Convert an object x to a formatted string
eval (str) Evaluates a string and returns an object
Tuple (s) Convert S to tuples
List (s) Convert S to List
Set (s) Convert S to Collection
Dict (s) Create a dictionary. D must be a sequence (key, value) tuple
Frozenset (s) Convert s to immutable collection
Chr (x) Convert an integer to a string
Ord (x) Converts a character to its integer value
Hex (x) Convert an integer to a hexadecimal string
Bin (x) Convert an integer to a binary string
Oct (x) Convert an integer to an octal string

It should be noted that the STR () and REPRT () functions may return different results. The repr () function typically creates an expression string that can be evaluated using eval () to re-create the object. The Ord () function returns an integer ordinal value of one character. In Unicode, this value is an integer code point. The Chr () function is used to convert integers into characters. In the function that creates the container, such as list (), tuple (), set (), the parameter can be any object that supports iterations, and all the items generated by the iteration will be used to populate the object to be created.

8. Boolean Expressions and Truth values

The and, or, and not keywords form a Boolean expression. The behavior of these operators is as follows:

operator Description
X or Y Returns y if X is false, otherwise returns X
X and Y Returns x if X is false, otherwise returns y
Not X If x is False, 1 is returned, otherwise 0 is returned.

When you use an expression to determine true or false values, true, any non-0 digits, non-empty strings, lists, tuples, or dictionaries will return true, and false, 0, none, and empty lists, tuples, and dictionaries will return false. Boolean expressions are evaluated from left to right, and the right operand is calculated only if needed.

9. Comparison and identity of objects

The equals operator (x = = y) can test whether the values of x and Y are equal. For lists and tuples, they are equal only if all of the elements are equal. For dictionaries, it returns true only if the keys for x and Y are the same, and all objects with the same key have equal values. Two sets the equality condition is that when compared with the = = operator, they have the same element.
The identity operator (x is y and x is not y) can test whether two objects refer to the same object in memory. Generally, x = = y, but x is not y.
The comparison operation can also be performed between two incompatible objects, such as a file and a floating-point number, but the returned result is arbitrary and may not be meaningful. In addition, it can also cause an exception.

10. Priority of Operations

The sequence of operations for the Python operator is as follows:

operator name
(...), [...], {...} Create tuples, lists, and dictionaries
S[i], S[i:j] Indexes and slices
S.attr Property
F (...) Function call
+x,-X, ~x Unary operators
X * * y Exponentiation (right-to-left operation)
X * y, x/y, x//Y, ×% y Multiplication, division, floor division, modulo
x + y, xy addition, subtraction
x << y, x >> y Shift
X & Y Bitwise-AND
x ^ y Bitwise XOR OR
x | Y Bitwise OR
x < y, x <= y comparison, identity, and sequence member checks
x > Y, x >= y
x = = y, x! = y
X is y, X was not y
X in S, X isn't in S
Not X Logical Non-
X and Y Logic and
X or Y Logical OR
Lambda args:expr anonymous functions

The order of operations is not determined by the type of x and Y in the table above. Therefore, you can redefine each operator even if it is a user-defined object.

11. Conditional expressions

A common programming pattern is to conditionally assign values based on the results of an expression, such as:

if a <= b:    minvalue = aelse:    minvalue = b

Use conditional expressions to simplify this code, for example:

minvalue = a if a <= b else b

In this type of expression, the first evaluation is the intermediate condition. If the result is true, then the expression to the left of the IF statement is evaluated, otherwise the expression after else is evaluated.

The [Python] operator and an expression

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.