Python重新分割()转义反斜杠

2024-04-25 01:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python重新在多个分隔符上拆分字符串,但它对我转义的反斜杠字符大喊大叫。在

我不确定要更改什么,因为当我在python中寻找转义反斜杠时,我看到的是正确的。。。在

import re
def get_asset_str(in_str):
    split = re.split(' |/|\\' , in_str)



Traceback (most recent call last):
  File "AssetCheck.py", line 15, in <module>
    get_asset_str(line)
  File "AssetCheck.py", line 4, in get_asset_str
    split = re.split(' |/|\\' , in_str)
  File "C:\Python27\lib\re.py", line 167, in split
    return _compile(pattern, flags).split(string, maxsplit)
  File "C:\Python27\lib\re.py", line 244, in _compile
    raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)

Tags: inpyregetliblineerrorasset
3条回答

试试看

import re
def get_asset_str(in_str):
    split = re.split(r' |/|\\' , in_str)

这应该是您想要的:

import re

in_str = """Hello there\good/morning"""
thelist = re.split(' |/|\\\\' , in_str)
print (thelist)

结果:

^{pr2}$

需要四舍五入转义反斜杠。或者使用原始输入(我更喜欢这个,但那只是我自己)

第一个反斜杠是在字符串文本级别转义第二个反斜杠。但是正则表达式引擎需要反斜杠也转义的,因为它也是正则表达式的一个特殊字符。在

使用“原始”字符串文本(例如r' |/|\\')或四倍反斜杠。在

相关问题 更多 >