问题遇到的现象和发生背景
我在体验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