Python如何拆分包含转义符作为分隔符的字符串?

2024-04-24 01:14:02 发布

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

如何在“\x”处拆分以下字符串?我遇到了麻烦,因为“\”是一个转义字符。你知道吗

MyString = 'A\x92\xa4\xbf'
delim = '"\"' + 'x'
MyList = MyString.split(delim)
print(MyList)

附加细节:4192A4BF是“低序列号”,显示为XCTU程序中Xbee无线电的序列号,Digi使用该程序配置Xbee无线电。你知道吗

在xbee上使用micropython检索序列号:serial = xbee.atcmd("SL")返回'A\x92\xa4\xbf',这是我所知的hex(A)后跟92A4BF。如果在“\x”处拆分,则可以提取与XTCU上相同的数字。你知道吗


Tags: 字符串程序细节split序列号printmystringxbee
1条回答
网友
1楼 · 发布于 2024-04-24 01:14:02

通过执行r'string'

试试这个:

MyString = r'A\x92\xa4\xbf'
delim = '\\' + 'x'  #OR simply: delim = '\\x'
MyList = MyString.split(delim)
print(MyList)

输出:

['A', '92', 'a4', 'bf']

此技术适用于任何转义序列(让我知道xD)\x,只需将分隔符设置为\\x工作示例:https://repl.it/@stupidlylogical/RawStringPython

工作原因:

Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.

说明:

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string.

更多:https://docs.python.org/2/reference/lexical_analysis.html#string-literals

相关问题 更多 >