Python笔记:字符串操作
a = 'test 123 dfg test'## 方法1len([i for i in a.split(' ') if i == test])## 方法2len(a.split('test'))-1
Python提取两个字符串之间的内容
import re str = '''/begin MEASUREMENT100LINKDISPLAYSYMBOL/end MEASUREMENT''' regex = r'/begin MEASUREMENT([\s\S]*)/end MEASUREMENT'matches = re.findall(regex, str)for match in matches: print(match)
import re str = 'test:100 end' regex = r'test:([\s\S]*)/end'matches = re.findall(regex, str)test = matches[0].strip()
字符删除、替换
删除空格
s = ' 123abcd456 '# 删除两边的空格print(s.strip())# 删除右边空格print(s.rstrip()) # 删除左边空格print(s.lstrip())# 删除两边的数字print(s.strip(' ').strip('123456'))# 删除两边的引号s = "'123abcd456'"print(s.strip("'"))
分割并去除空格
string = " hello , world !"string = [x.strip() for x in string.split(',')]
将格式化字符转换为字典
string = "dst='192.168.0.1',src='192.168.1.2'"fields = dict((field.split('=') for field in string.split(',')))fields = dict(((lambda a:(a[0].strip("'"),a[1].strip("'"))) (field.split('=')) for field in string.split(',')))
>>> fields{'dst': "'192.168.0.1'", 'src': "'192.168.1.2'"}
删除(替换)任意位置字符
s = '11233aabcdd41556'# 删除某个特定字符print(ss.replace('1', ''))# 同时删除不同字符import reprint(re.sub('[1a]', '', s))
--THE END--
赞 (0)