This article summarizes some of the basic Python uses I’ve encountered so far, and I’ve recorded them here for later retrieval when I forget them. Many official Python documentation references are included in this article, and links are available in each section.

First, judge whether a value is true

True value detection

An object is checked to see if its value is true when used in an if or while statement, or as an operand of the following Boolean operations.

By default, an object whose class defines an __Bool__ () function that returns False or an __len__() function that returns 0 is False. Otherwise, it is true.

  • NoneandFalseIs a fake
  • Zero of any numeric type is false:0.0.0.0j.Decimal(0).Fraction(0, 1)
  • Empty sequences and sets are false:' '.(a).[].{}.set().range(0)

Boolean operation:

operation The results of
x or y ifxIf false, returnyOtherwise returnx
x and y ifxIf false, returnxOtherwise returny
not x ifxIf false, returnTrueOtherwise returnFalse

The Boolean operators or, and, and not have higher priorities. A and B or NOT C are evaluated in the order (a and b) or (not C), not C is evaluated first, then (A and b), and then the whole.

X and y and x or y are both short-circuited, which means that if you already know something from x, you don’t evaluate y.

For example, x and y if x is false, then x and y must be false, you don’t have to evaluate y to get the result, you just return x, the operand y is not executed.

X or y, if x is true, then x or y must be true, you don’t have to evaluate y to get the result, you just return x, the expression y is not executed.

x = []

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

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

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

Second, the comparison

There are eight comparisons, all of which have the same priority, but the comparison has a higher priority than the Boolean.

operation meaning
< Less than
< = Less than or equal to
> Is greater than
> = Greater than or equal to
= = Is equal to the
! = Is not equal to
is Yes (object identity)
is not Not (negative object identity)

Except for the different types of numbers, all the other different types are considered unequal. TypeError is raised when inappropriate types are compared.

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 the code

Can pass __lt__ (), __le__ (), __gt__ (), __ge__ (), __eq__ () function comparison behavior custom object.

X equals equals y is said to be equal as long as x and y represent the same value, but is requires that x be the same object. == and is are the same for class objects.

e = [1.2]
f = [1.2]

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

A tuple is an immutable type, in the example below c = = d and c is the result of the d all is True, and print out the c, d the same memory address, Python did some optimization in the behind, the value of d and c is the same, so in the definition of d, direct reuse has created the c value, 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 the code

Also in and not in, x in s is evaluated to True if x is a member of S, and False otherwise. Not in is just the opposite.

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

For more details, see comparison.

3. Determine the type of a value

  1. Using isinstance

Isinstance (object, classinfo) returns True if the object argument is an instance of the classInfo argument or an instance of a subclass of the classInfo argument.

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 the code
  1. Using the type

Type () returns the type of the object. Isinstance is recommended when determining the type of an object because it allows for subclasses.

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

Four, calculate

Numeric types

operation The results of
x + y xyAnd of the
x - y xyThe difference between the
x * y xyThe product of the
x / y xyThe dealer
x // y xyThe quotient of
x % y x / yThe remainder of
-x xThe not
+x xThe same
abs(x) xThe absolute value or magnitude of theta
int(x) willxConvert to integer
float(x) willxConvert to floating point
pow(x, y) xypower
x ** y xypower

The result of x/y is always a floating point. 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 the code
operation The results of
math.trunc(x) willxTruncate to an integer
round(x[, n]) willxRound to zeronHalf of a decimal number will be rounded to an even number if omittedn, the default is0
math.floor(x) Integral< =x, round down
math.ceil(x) Integral> =x, round 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 the code

Json and string conversion

json

  1. Json to stringjson.dumps()
  2. String to JSONjson.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 the code

6. Methods related to list

Sequence types

operation The results of
x in s ifsOne of the terms is equal tox, the results forTrue, otherwise the result isFalse.
x not in s ifsOne of the terms is equal tox, the results forFalse, otherwise the result isTrue
s + t Joining togetherst
s * norn * s The equivalent ofneachsFor Mosaic
s[i] sThe firstiItem,ifrom0Start.
s[i:j] sfromitojThe section of
s[i:j:k] sfromitojSlice each index intervalk
len(s) sThe length of the
min(s) sThe smallest term of theta
max(s) sThe largest term of theta
s.index(x[, i[, j]]) insIs the first one that appears inxIndex location (in indexiOr greater thani, less than indexjThe location of the)
s.count(x) insIn thexThe total number of occurrences
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 the code

List related, list related methods:

  1. list.append(x)

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

  1. list.extend(iterable)

Add all items from the iterable to the list. 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)

Remove the first item in the list with value x. If there is no item with a value of x, a ValueError is raised.

  1. list.pop([i])

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

  1. list.clear()

Removes 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, 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 the code

7, STR related methods

Text sequence type – STR

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

Return 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, return -1.

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

Performs a format string operation. STR can contain text literals and {}, where {} is the index of the positional argument or the name of the keyword argument.

x = 'Just write {0}. {a}.'.format('sentence', a='ha ha')
print(x) # Write random sentences. Ha ha
Copy the code
  1. str.join(iterable)

Returns a character consisting of values in an iterable object. STR is the space between elements.

y = ['base'.'king'.'crazy'.'down'.'yeah'.'〠_〠']
print(' '.join(y)) # Fund falls, tut 〠_〠
Copy the code
  1. str.split(sep=None, maxsplit=-1)

Returns a list of words in a string, using sep as the delimiter. Maxsplit sets the number of separations. If maxsplit is not declared or maxsplit is declared with a value of -1, there is no limit to the number of splits.

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

This can be used with str.join(iterable).

  1. str.lower()

Returns a string of characters converted to lowercase.

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

Returns a string of characters converted to uppercase.

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

Replace all old strings that appear in the string with the new string, and if there is a count, replace only the first count strings.

a = 'The a string a has no a in it.'
print(a.replace('a'.' ')) There are no English letters in this string
Copy the code

Loop through objects that support iteration

cycle

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

2. When iterating through a sequence, use enumerate to return an iterable through which to retrieve both the index and the value of the corresponding position. This method is equivalent to:

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

Example:

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

# 0 c
# 1 c
# 2 c
Copy the code

3. When traversing the dictionary, use items() to get the key and value 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 the code

4. Iterate over 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
Copy the code

9. Date related methods

Documented in Several Date-related uses in Python.