我在体验re.split功能的时候,把同一个str用不同的字符分隔,结果,5个测试中,123都正常输出,但是print('4',list1)没能正常输出,请帮忙找下原因,谢谢。
import re
pattern=' '
str1='123 45@678$345*67/890'
list1=re.split(pattern,str1)
print('1',list1)
pattern='@'
str1='123 45@678$345*67/890'
list1=re.split(pattern,str1)
print('2',list1)
pattern='$'
str1='123 45@678$345*67/890'
list1=re.split(pattern,str1)
print('3',list1)
pattern='*'
str1='123 45@678$345*67/890'
list1=re.split(pattern,str1)
print('4',list1)
pattern='/'
str1='123 45@678$345*67/890'
list1=re.split(pattern,str1)
print('5',list1)
print('6',str1.split('$'))
# 1 ['123', '45@678$345*67/890']
# 2 ['123 45', '678$345*67/890']
# 3 ['123 45@678$345*67/890', '']
# 5 ['123 45@678$345*67', '890']
# 6 ['123 45@678', '345*67/890']
1 ['123', '45@678$34567/890']
2 ['123 45', '678$34567/890']
3 ['123 45@678$345*67/890', '']
Traceback (most recent call last):
File "D:/我的坚果云/py lianxi/lianxi 1/lianxi1.py", line 6703, in
list1=re.split(pattern,str1)
File "C:\Python37\lib\re.py", line 215, in split
return _compile(pattern, flags).split(string, maxsplit)
File "C:\Python37\lib\re.py", line 288, in _compile
p = sre_compile.compile(pattern, flags)
File "C:\Python37\lib\sre_compile.py", line 764, in compile
p = sre_parse.parse(p, flags)
File "C:\Python37\lib\sre_parse.py", line 924, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "C:\Python37\lib\sre_parse.py", line 420, in _parse_sub
not nested and not items))
File "C:\Python37\lib\sre_parse.py", line 645, in _parse
source.tell() - here + len(this))
re.error: nothing to repeat at position 0
pattern=''
str1='123 45@678$34567/890'
list1=re.split(pattern,str1)
print('4',list1)
用'*',分隔str1
因为$和*在正则表达式是有含义的,前者表示匹配末尾字符的意思,后者表示前一个字符重复0至n次(因为没有前一个字符所以报错)所以对于3和4,你需要分别在这两个符号pattern前加入\转义字符,才能达到你的意思