python 学习-函数-匹配替换等操作

1.re.match匹配

re.match(pattern, string)`:从字符串的开头匹配正则表达式,返回一个匹配对象。如果没有找到匹配的子串,返回 `None`

str = ' choice: ['app1-ui','app2-ui']'
#查找str是否以空格开头第一个有效字符是choice的的行,如果是打印ok
if re.match(r'\s+choice.*',str):
    print('ok')
#ok
 

2.str.split(':')[-1]分隔

对str字符串以某个字符(:)为分隔符进行分隔,并取分隔后的最后一个字符串

str = 'choice : ['app1-ui','app2-test']'
#以:为分隔符,取最后一个字符串
str.split(':')[-1]
#str=['app1-ui','app2-test']

 

3.str.replace(s1,s2) 替换

对字符串str,将str中的字符s1替换为s2

str='['app1-ui','app2-ui']'
#将[]及引号'都替换为空字符
str= str.replace('[','').replace(']', '').replace('\'', '')
#str=app1-ui,app2-ui

 

4.re.sub替换

str.replace只能替换指定的字符串,而re.sub可以替换正则子串,可以匹配到整行进行替换

re.sub(pattern, replace, string):在字符串中查找所有匹配正则表达式的子串,并将其替换为指定的字符串。

str = 'sonar.modules=$modlue_name'
if "$moudle_name" in str:
#若str是sonar开头的字符,将str字符串替换为(#+str)字符串
    line = re.sub(r'[sonar].*','#'+str,str

5.str.strip()   str.rstrip() 删除字符

strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

rstrip() 删除 string 字符串末尾的指定字符(默认为空格或换行符)

str = '233332'
    print(str.strip('2'))
    print(str.rstrip('2'))
#3333
#23333

 

6.复制文件

import shutil

src_file = '/path/to/source/file.txt'
dst_file = '/path/to/destination/file.txt'
shutil.copy2(src_file, dst_file)

 

 
posted @ 2023-08-14 11:03  潇潇暮鱼鱼  阅读(123)  评论(0)    收藏  举报