Common built-in modules

Common built-in modules mainly have:

import time
import random
import datetime
import re
import json
import sprite

Before using, please import the corresponding module. This tutorial and the tutorial of the previous function library are all written in Python 3.x based version.

Ⅰ. time

Time module for time acquisition and conversion

1 time.sleep()

time.sleep()Used to take a break for a specified time while the program is executing, in seconds.for example:

for i in range(5):
    print(i)
    time.sleep(1)

operation result:

0
1
2
3
4

The function of this code is : Print a number every 1 second, where range(5) is used to generate an iterator object, which can be understood as generating a list range(5) => [0, 1, 2, 3 , 4], range(5) defaults from 0 and generates 5 times. You can specify the starting point, for example rang(1, 6) = [1, 2, 3, 4, 4]\ (left include, right does not include ); for .. in .. is used for traversing Iterative object

2 time.localtime()

time.localtime()Used to get local time and generate as a time tuple

print(time.localtime())

operation result:

time.struct_time(tm_year=2018, tm_mon=8, tm_mday=20, tm_hour=18, tm_min=3, tm_sec=18, tm_wday=0, tm_yday=232, tm_isdst=0)
index Attribute Values
0 tm_year (E.g.:2015)
1 tm_mon(month) 1-12
2 tm_mday(day) 1-31
3 tm_hour 0-23
4 tm_min(Minute) 0-59
5 tm_sec(second) 0-61(60 represents leap second, 61 is reserved for historical reasons)
6 tm_wday(Day of the week) 0-6(0 means Monday)
7 tm_yday(the day of the year) 1-366
8 tm_isdst(Whether it is daylight saving time) 0,1,-1(-1 for daylight saving time)

3 time.time()

Returns the timestamp of the current time(floating seconds after 1970元), which can be used to measure the running time of a certain piece of code

start_time = time.time()

a = 0
for i in range(1, 101):
    a += i

end_time = time.time()

print('The value of a is:%s' %(a))
print('Running for loops%s' %(end_time - start_time))

operation result:

The value of a is:5050
Run for loop, a total of 100 cycles, the total time is:0.000190258026123

a += i is a simplified notation, equivalent to a = a + i, similar usage can also be applied to subtraction \ (a -= i), multiplication \ (a *= i), division \ ( a /= i)etc.

Ⅱ. randome

Mainly has the function of generating random numbers, generating random numbers within a specified range, and randomly selecting

1 random.random()

Generating a random float within the 0-1

for i in range(5):
    print(random.random())

operation result:

0.0692932045127
0.00866250612738
0.223208213488
0.215825885145
0.815881998416

random.uniform()Used to generate random numbers within the specified range, such as random.uniform(1, 10), to generate random numbers within 1-10

2 random.randint()

Generate a random integer within the specified range

for i in range(5):
    print(random.randin(10, 100))

operation result:

23
67
60
34
83

random.randint()When filling in the range, the first parameter is the lower limit, the second parameter is the upper limit, and the lower limit parameter should be less than the upper limit.

3 random.choice()

Randomly select an element in an iterable object

a = 'Kuture'
b = ['Mr.Li', 'Keven', 'Lily', 'Potter', 'Marry']
c = (128, 64, 1024, 512, 16)


# Definition method
def rand_method(num):

    for i in range(num):

        rand_str = random.choice(a)
        rand_list = random.choice(b)
        rand_tuple = random.choice(c)

        print('Str: ', rand_str)
        print('List: ', rand_list)
        print('Tuple: ', rand_tuple)
        print('-' * 15)

# The way of transfer
rand_method(3)

operation result:

Str:  K
List:  Mr.Li
Tuple:  16
---------------
Str:  t
List:  Marry
Tuple:  128
---------------
Str:  t
List:  Lily
Tuple:  1024
---------------

Common iteration objects in Python are string, list, tuple, dict, and so on.This section of the code uses a method, which is equivalent to putting a piece of code in a block of code, which helps to reduce the repetitive writing of commonly used functions.The function of this method is to repeat the corresponding number of loops according to the parameters passed in, where a, b, and c are the string string, list, and tuple types respectively. In the for loop, use random.choice() to randomly select from them. Give an element.Print() prints the corresponding result in the terminal. '-' * 15 in print('-' * 15) indicates how many times the string is displayed repeatedly.

Ⅲ. datetime

Datetime is often used to get information such as date, date interval, time zone, etc. Here are the two commonly used modules date and datetime.date(to)() and datetime.now()

1 Introduction to datetime module

The datetime module contains the following classes::

classification Description
date Date object, commonly used attributes are year, month, day
time Time object
datetime Date time object, commonly used attributes are hour, minute, second, microsecond
datetime_CAPI Date time object C language interface
timedelta Time interval, the length between two time points
tzinfo Time zone information object

Constants contained in the datetime module:

Constant Function Description Usage Return Value
MAXYEAR Returns the largest year that can be represented datetime.MAXYEAR 9999
MINYEAR Returns the smallest year that can be represented datetime.MINYEAR 1

2 datetime.date.today()

Get the current date

# Create an instantiated object
a = datetime.date.today()

b = a.year
c = a.month
d = a.day

print('Date: ', a)
print('Year: ', b)
print('Month: ', c)
print('Day: ', d)

operation result:

Date: 2018-08-21
Year: 2018
Month: 8
Day: 21

a is an instantiated object created by datetime.date.today()

3 datetime.datetime.now()

Get the current date and time, including the year, month, day, hour, minute, second

a = datetime.datetime.now()
time.sleep(random.randint(1, 10))
b = datetime.datetime.now()

print('Time difference:', b - a)

operation result:

Time difference: 0:00:03.005850

Randomly generate time rest time, b - a represents the time difference between point a and point b. If you do not want to display the format: (b-a).seconds => 3

Ⅳ. re

re is a regular expression module in python, often used to match queries

Regular expressions themselves are a small, highly specialized programming language, and in Python, the inline integrated re module can be used directly to implement regular matching. The regular expression pattern is compiled into a series of bytecodes that are executed by a matching engine written in C.

re.match() and re.search()

a = 'Kuture is a Developer for Microduino'

result_search = re.search(r'for(.*)', a)
result_match = re.match(r'Kuture is a Developer for(.*)', a)

if result_search:

    print('Search: ', result_search.group(1))
if result_match:

    print('Match: ', result_match.group(1))

operation result:

Search: Microduino
Match: Microduino

result__search uses re.search(), where 'for(.*)' represents a string found from the a string containing the start of for and intercepts any elements after the for , '.' means to match any element, '*' means the number of matches is 0-∞. Result_match uses re.match(), the match needs to be matched from the beginning, and the match function is the same as search(). _mathc() matches from the beginning of the string, search() looks for a match within the string

Normal characters and 11 metacharacters

Normal character match itself abc abc
. Match any character except the newline "\n"\ (can also match newline in DOTALL mode) a.c abc
\ Escape character to change the original character a.c;a\c a.c;a\c
* Match the previous character 0 or more times abc* ab;abccc
+ Match the previous character 1 time or unlimited abc+ abc;abccc
? Match one character 0 times or 1 time abc? ab;abc
^ Matches the beginning of the string. Match the beginning of each line in multi-line mode ^abc abc
$ Matches the end of the string, matching the end of each line in multi-line mode abc$ abc
\ or. Matches \ any one of the left and right expressions, matching from left to right. If \ is not included in (), its range is the entire regular expression. abc\ def abcdef
{} {m} Match the previous character m times, {m,n} matches the previous character m to n times, if n is omitted, match m to infinity ab{1,2}c abcabbc
[] character set. The corresponding position can be any character in the character set. Characters in a character set can be listed one by one or given a range, such as [abc] or [a-c]. [^abc] means negation, that is, not abc. All special characters lose their original special meaning in the character set. Use the \backslash escape to restore the special meaning of special characters. a[bcd]e abeaceade
() The enclosed expression will be grouped, starting from the left side of the expression without encountering a grouped left parenthesis "(", number +1. The grouping expression as a whole can be followed by a quantifier. \ in the expression only Valid in this group. (abc){2} a(123\ 456)c abcabca456c

Here we need to emphasize the role of backslash \:

  • The backslash is followed by a metacharacter to remove special functions;(which is to special characters into ordinary characters)

  • The backslash is followed by ordinary characters to achieve special functions.;(Predefined characters)

  • The string that matches the word group corresponding to the sequence number.

Predefined character set

\d digital:[0-9] a\bc a1c
\D Non-number:[^\d] a\Dc abc
\s Match any whitespace characters:[<Space>\t\r\n\f\v] a\sc a c
\S Non-blank character:[^\s] a\Sc abc
\w Match any word character including underscore:[A-Za-z0-9_] a\wc abc
\W Match non-alphabetic characters, that is, match special characters a\Wc a c
\A Match only the beginning of the string, like ^ \Aabc abc
\Z Match only the end of the string, like $ abc\Z abc
\b Matches between \w and \W, that is, the matching word boundary matches a word boundary, which is the position between the word and the space. For example, 'er\b' can match 'er' in "never" but not 'er' in "verb". \babc\b a\b!bc Space abc Space a!bc
\B [^\b] a\Bbc abc

Ⅴ. json

Json is commonly used to encode and decode JSON objects. Only the decoding of JOSN strings into Python objects is explained here.

Currently encoding Python objects into JSON strings is not yet supported in mDesigner.

datas = "[{'name': 'Mr.Zhang', 'age': 18, 'gender': 'male'},{'name': 'Lily', 'age': 17, 'gender': 'famale'},{'name': 'Maly', 'age': 19, 'gender': 'famale'}]"

print('loads_before: ', type(datas))

datas = datas.replace("'", '"')
datas_loads = json.loads(datas)

print('dumps_after: ', type(datas_loads))

Json.loads() does not support single quotes, so convert single quotes to double quotes before use. Datas.replace("'",'"') is used to replace single quotes

operation result:

loads_before:  <class 'str'>
dumps_after:  <class 'list'>

As you can see from the results, before the datas conversion is a string, converted into a list object