我有这样的字符串
LASTSCAN:C:\Users\Bob\Scripts\VisualizeData\doc\placeholder.PNG:1557883221.11
字符串的格式为[Command][File path][Timestamp]
。当前它由冒号分隔,但文件路径也有一个冒号。有时,字符串的格式可能会更改,但始终用冒号分隔。例如:
SCAN:2000:25:-12.5:12.5:C:\Users\Potato\potato.PNG:1557884143.93
此字符串的签名为[Command][Frames][Speed][Start][Stop][File path][Timestamp]
如何拆分输入字符串以获得这样的输出?
['LASTSCAN', 'C:\Users\Bob\Scripts\VisualizeData\doc\placeholder.PNG', '1557883221.11']
第二个示例的预期输出
['SCAN', '2000', '25', '-12.5', '12.5', 'C:\Users\Potato\potato.PNG', '1557884143.93']
答案 0 :(得分:5)
尝试按正则表达式模式:(?!\\)
进行分割:
input = "LASTSCAN:C:\Users\Bob\Scripts\VisualizeData\doc\placeholder.PNG:1557883221.11"
output = re.split(r':(?!\\)', input)
print(output)
['LASTSCAN', 'C:\\Users\\Bob\\Scripts\\VisualizeData\\doc\\placeholder.PNG', '1557883221.11']
逻辑是在不是的任何冒号上进行分割,并紧随其后的是路径分隔符。这样可以避免将文件路径中的:
定位为分割点。
答案 1 :(得分:1)
如果可以确定要保留的“:”后面紧跟一个“ \”,并且周围将没有其他“ \”。您可以尝试这样的事情。
new = string.split(':')
for i in range(new):
if new[i][0] == "\":
new[i-1] += new.pop(i)
答案 2 :(得分:1)
为什么不使用正则表达式:
import re
s = 'SCAN:2000:25:-12.5:12.5:C:/Users/Potato/potato.PNG:1557884143.93'
print(re.split(':(?!/)',s))
输出:
['SCAN', '2000', '25', '-12.5', '12.5', 'C:/Users/Potato/potato.PNG', '1557884143.93']
而且,至少对于我来说,您还必须将\
更改为/
,并在正则表达式中也要更改。