Tell you some basic Python methods you don't know about

Posted by Henks on Tue, 28 Dec 2021 00:57:28 +0100

When in if perhaps while Statement, or as the operand of the following Boolean operation, an object will be checked to determine whether a value is true

By default, an object, if its class defines an object that returns False __bool__() Function, or a function that returns 0 __len__() Function, then it will be judged as false. In other cases, it is true.

  • None and False are False
  • Zeros of any number type are false: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • Empty sequences and sets are false: '', (), [], {}, set(), range(0)

Boolean operation:

operationresult
x or yReturns y if x is false, otherwise returns X
x and yIf x is false, X is returned, otherwise y is returned
not xReturns True if x is False, False otherwise

Or, and, and not are three Boolean operators with higher priority. Not has the highest priority. The evaluation order of a and b or not c is (a and b) or (not c). Not C is evaluated first, then (a and b), and then the whole.

Both x and y and x or y have the function of short circuit, that is, if the result can be obtained from x, y will not be evaluated.

For example, if the value of x and y is false, x and y must be false. The result can be obtained without evaluating y. x is returned directly, and the operand y will not be executed.

X or Y, if x is true, then x or y must be true. You can get the result without evaluating y, directly return x, and the expression y will not be executed.

x = []

def y():
    print('y')
    return 1

a = x and y()
b = bool(x and y())

print(a, b) # [] False
 Copy code

2, Compare

There are 8 comparison operations in total. The priority of these 8 comparison operations is the same, but the priority of comparison operation is higher than that of Boolean operation.

operationsignificance
<less than
<=Less than or equal to
>greater than
>=Greater than or equal to
==be equal to
!=Not equal to
isYes (object ID)
is notNo (negative object ID)

Except for different number types, all other different types are considered unequal. TypeError is thrown when comparing inappropriate types.

from datetime import datetime, timedelta

now = datetime.now()
yesterday = now + timedelta(days=-1)

print(now > yesterday) # True

print(2 <= 1.5) # False

print(2 <= now) # TypeError: '<=' not supported between instances of 'int' and 'datetime.datetime'
Copy code

Can pass __lt__(), __le__(), __gt__(), __ge__() , __eq__() And other functions to customize the comparison behavior of objects.

x == y is considered equal as long as the values represented by X and y are the same, but is requires that x is the same object. For class objects = = and is are the same.

e = [1, 2]
f = [1, 2]

print(e == f) # True
print(e is f) # False
print(id(e), id(f)) # 4479741616 4478061536
 Copy code

Tuples are immutable types. In the following example, the results of c == d and c is d are True, and the memory addresses of c and d are the same, indicating that Python has made some optimization behind it. The values of d and c are the same. Therefore, when defining d, the created values of c are directly reused, and c and d point to the same object.

c = (1, 2)
d = (1, 2)

print(c == d) # True
print(c is d) # True
print(id(c), id(d)) # 4470112416 4470112416
 Copy code

also in and not in , x in s is evaluated as True if x is a member of s, otherwise it is False. not in is the opposite.

print(1 in [1, 2, 3]) # True
print(1 not in (1, 2, 3)) # False
 Copy code

For more details, you can view: compare.

3, Determine the type of a value

  1. use isinstance

isinstance(object, classinfo). If the object parameter is an instance of the classinfo parameter or an instance of a subclass of the classinfo parameter, isinstance(object, classinfo) returns True.

Python has these built-in constructors:

bool(),int(),float(),str(),list(),dict(),object(),range(),set(),slice(),tuple(),bytearray(),bytes(),complex() , frozenset(), etc.

g = 'g'
h = 1
i = [1, 2]
j = { 'j': 1 }

print(isinstance(g, str)) # True
print(isinstance(h, int)) # True
print(isinstance(i, list)) # True
print(isinstance(j, dict)) # True
 Copy code
  1. use type

type() returns the type of the object. isinstance is recommended when determining the object type because it takes subclasses into account.

print(type('g') == str) # True
print(type(1) == int) # True
 Copy code

4, Calculate

Number type

operationresult
x + ySum of x and y
x - yDifference between x and y
x * yProduct of x and y
x / yQuotient of x and y
x // yQuotient of x and y
x % yRemainder of x / y
-xx inversion
+xx invariant
abs(x)The absolute value or size of x
int(x)Convert x to integer
float(x)Convert x to floating point number
pow(x, y)y power of x
x ** yy power of x

The result of x / y is always a floating point number. x // y is the quotient of x / y rounded down.

k = 2 / 1
print(k) # 2.0

l = 1 / 2
m = 1 // 2

print(l, m) # 0.5 0

n = 3.5 % 2

print(n) # 1.5
 Copy code
operationresult
math.trunc(x)Truncate x to an integer
round(x[, n])Round x to N decimal places, and half of the value will be rounded to an even number. If n is omitted, it defaults to 0
math.floor(x)Integral < = x, rounded down
math.ceil(x)Integral >=X, rounded up
o = math.trunc(1.2)
p = round(1.2265, 2)
q = round(2.5)
r = math.floor(1.2)
s = math.ceil(1.2)

print(o, p, q, r, s) # 1 1.23 2 1 2
 Copy code

5, json and string conversion

json

  1. json to string dumps()
  2. String to json loads()
import json

t = [
    'a',
    1,
    {
        'b': [1, 2, 3]
    }
]

t_str = json.dumps(t)
t_json = json.loads(t_str)

print(t_str, t_json[2]['b'][0]) # '["a", 1, {"b": [1, 2, 3]}]' 1
 Copy code

6, list related methods

Sequence type

operationresult
x in sIf one item in s is equal to x, the result is True, otherwise the result is False.
x not in sIf one item in s is equal to x, the result is False, otherwise the result is True
s + tSplice s and t
s * n or n * sEquivalent to splicing n s
s[i]Item i of s, i starts from 0.
s[i:j]Slice of s from i to j
s[i:j:k]s slices from i to j, each index interval k
len(s)Length of s
min(s)The smallest item of s
max(s)The largest item of s
s.index(x[, i[, j]])Index position of the first x appearing in s (at index i or greater than i and less than index j)
s.count(x)Total number of occurrences of x in s
u = [1, 2]
v = [3, 4, 5, 6, 7, 8]

print(1 in u) # True
print(3 not in u) # True
print(u + v) # [1, 2, 3, 4, 5, 6, 7, 8]
print([None] * 2) # [None, None]
print(u[0]) # 1
print(v[1: 3]) # [4, 5]
print(v[0: 5: 1]) # [3, 4, 5, 6, 7]
print(len(u)) # 2
print(min(v)) # 3
print(max(v)) # 8
print(v.index(6)) # 3
print(v.count(1)) # 0
 Copy code

list related , list method:

  1. list.append(x)

Add an item to the end of the list. Equivalent to a[len(a):] = [x].

  1. list.extend(iterable)

Add all items in the iteratable object iterable to the list. Equivalent to a[len(a):] = [x].

  1. list.insert(i, x)

Inserts an item into a given location. Insert x before the item with index i.

  1. list.remove(x)

Removes the first item in the list with a value of x. If there is no item with a value of x, it is thrown ValueError .

  1. list.pop([i])

Removes an item at a given location in the list and returns it. If the index i is not declared, the last item in the list is removed and returned.

  1. list.clear()

Remove all items from the list. Equivalent to del a [:].

d = [1, 2]
d.append(3)
print(d) # [1, 2, 3]

d.extend((3, 4, 5))
print(d) # [1, 2, 3, 3, 4, 5]

d.insert(0, 10)
print(d) # [10, 1, 2, 3, 3, 4, 5]

d.remove(3) # [10, 1, 2, 3, 4, 5]
print(d)

d.pop() # [10, 1, 2, 3, 4]
print(d)

d.clear() # []
print(d)
Copy code

7, Related methods of str

Text sequence type - str

  1. str.find(sub[, start[, end]])

Returns the first lowest index position of the substring sub that appears in the string slice s[start:end]. If the substring sub is not found, - 1 is returned.

w = 'abc'.find('a')
print(w) # 0
 Copy code
  1. str.format(args, kwargs)

Perform a format string operation. str can contain text literal and {}, where {} is the index of location parameter or the name of keyword parameter.

x = 'Just write something {0}. {a}'.format('sentence', a='ha-ha')
print(x) # Write some sentences casually ha-ha
 Copy code
  1. str.join(iterable)

Returns a character consisting of values in an iteratable object. str is the interval between elements.

y = ['base', 'gold', 'Crazy', 'fall', ',Tut', '〠_〠']
print(''.join(y)) # The fund fell sharply, tut 〠
Copy code
  1. str.split(sep=None, maxsplit=-1)

Returns a list of words in a string, using sep as the separator. Maxplit sets the number of separators. If maxplit is not declared or the value of maxplit is declared as - 1, there is no limit on the number of separators.

b = 'a, b, c, d, e'
print(b.split(',')) # ['a', ' b', ' c', ' d', ' e']
print(b.split(',', 2)) # ['a', ' b', ' c, d, e']
Copy code

This can be used corresponding to str.join(iterable).

  1. str.lower()

Returns a string that converts characters to lowercase characters.

z = 'Xyz'
print(z.lower()) # xyz
 Copy code
  1. str.upper()

Returns a string that converts characters to uppercase characters.

c = 'xyz'
print(c.upper()) # XYZ
 Copy code
  1. str.replace(old, new[, count])

Replace all old strings in the string with the new string new. If there is a count, only the first count strings will be replaced.

a = 'this a character string a Inside no a There are English letters a'
print(a.replace('a', '')) #There are no English letters in this string
 Copy code

8, Loop through objects that support iteration

loop

  1. Simple traversal, using for in:
for e in ('a', 'b', 'c'):
    print(e)
Copy code

2. When traversing the sequence, use enumerate , return an iteratable object, through which you can get the index and the value of the corresponding position at the same time. This method is equivalent to:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
 Copy code

example:

for i, f in enumerate(['a', 'b', 'c']):
    print(i, e)

# 0 c
# 1 c
# 2 c
 Copy code

3. When traversing the dictionary, use items() to get the keys and values of the dictionary at the same time.

g = {
    'a': 10,
    'b': 20,
    'c': 30,
}
for k, v in g.items():
    print(k, v)

# a 10
# b 20
# c 30
 Copy code

4. Traverse two or more objects, using zip()

h_arr = [1, 2, 3]
i_arr = [4, 5]

for h, i in zip(h_arr, i_arr):
    print(h, i)

# 1 4
# 2 5

Those who like little fat people hurry up for three times, otherwise they can't find little fat people~

reference

 

Topics: Python Django list Tornado virtualenv