Python learning road _day_19 (commonly used module 3)

1. re module

Python regular expression:

raw string:

The raw string form is to add an r or R prefix to the normal character transfer literal, for example:

R’abcdefg’

r’C:\course\python\progs’

There is only one special thing about the original string, that is, the backslash character '\' in it is not used as an escape character, and remains as it is in the corresponding string object. The backslash character before single and double quotes is still used as escape. symbol.

Metacharacters (special characters)

The regular expression package specifies a set of special characters, called metacharacters. They play a special role when matching strings. There are 14 such characters in total:

. ^ $ * + ? \ {} [] ()

Main operation:

In the function description below, the pattern in the parameter expresses the pattern string (the string describing the regular expression), the string expresses the string to be processed, and the repl expresses the replacement string, which is another string in the operation.

  1. Generate a regular expression object: re.compile(pattern, flag=0)

r1 = re.compile(‘abc’)

  1. Search: re.search(pattern,string,flag=0)

Retrieves the substring in string that matches pattern. Returns an object of type match if found; otherwise, returns None. The relevant information of successful matching is recorded in the match object, which can be checked and used as needed. You can also use the match object simply as a truth value for logical judgment.

  1. Match: re.match(pattern,string,flag=0)

Checks whether strings have a prefix matching pattern. Returns the corresponding match object when the match is successful, otherwise returns None. E.g:

re.search(r1, 'aaabcbcbabcb') # will match successfully

re.match(r1, 'aaabcbcbabcb') #return None

  1. Separation: re.split(pattern,string,maxspilt=0,flags=0)

Use pattern as the separator string to split the string. The parameter maxsplit specifies the maximum number of splits, and 0 indicates that the entire string is required to be processed. The function returns a table of strings separated by values. For example:

re.split(‘ ‘,’abc abb are not the same’)

get: ['abc', 'abb', 'are', 'not', 'the', 'same']

re.split('', '1 2 3 4')#Separates several empty strings

得到:[‘1’, ‘2’, ‘’, ‘3’, ’’, ‘’, ‘4’]

  1. 找出所有匹配串:re.finadall(pattern, string, flag=0)

返回一个表,表中元素是按顺序给出的string里与pattern匹配的各个子串(从左到右,非重叠的).如果模式里只有常规字符,做这种匹配的价值不大,因为结果里的所有字符串相同.但用一般的正则表达式,情况就可能不同.

 

  1. subprocess模块

 

sub 子

process 进程

 

表示正在进行的进程,没当打开一个程序就会开启一个进程

每个进程包含进行程序所需要的所有资源

正常情况下,不可以跨进进程访问数据

但是有些情况就需要访问别的进程数据

提供一个叫做管道的对象,专用于跨进程通讯

 

作用:用于执行系统命令

 

常用方法:

run 返回一个表示执行结果的对象

call 返回的执行的状态码

总结: subprocess的好处是可以获取指令的执行结

subprocess执行指令时,可以在进程中

 

 

Related Posts