nathancy
nathancy

Reputation: 46610

How to split and ignore separators in file path string using Python

I have a string like this

LASTSCAN:C:\Users\Bob\Scripts\VisualizeData\doc\placeholder.PNG:1557883221.11

The format of the string is [Command][File path][Timestamp]. Currently it is separated by colons but the file path also has a colon. Other times the format of the string may change but it is always separated by a colon. For instance:

SCAN:2000:25:-12.5:12.5:C:\Users\Potato\potato.PNG:1557884143.93

This string has a signature of [Command][Frames][Speed][Start][Stop][File path][Timestamp]

How do I split the input string to obtain a output like this?

['LASTSCAN', 'C:\Users\Bob\Scripts\VisualizeData\doc\placeholder.PNG', '1557883221.11']

Expected output for 2nd example

['SCAN', '2000', '25', '-12.5', '12.5', 'C:\Users\Potato\potato.PNG', '1557884143.93']

Upvotes: 1

Views: 543

Answers (3)

U13-Forward
U13-Forward

Reputation: 71580

Why not using regex:

import re
s = 'SCAN:2000:25:-12.5:12.5:C:/Users/Potato/potato.PNG:1557884143.93'
print(re.split(':(?!/)',s))

Output:

['SCAN', '2000', '25', '-12.5', '12.5', 'C:/Users/Potato/potato.PNG', '1557884143.93']

Also, at least for me, you have to change \ to /, and in the regex expression as well.

Upvotes: 1

Kinobeon
Kinobeon

Reputation: 11

If you can be certain the ":" you wish to keep is immediately followed by a "\" and that there will be no other "\" around. You could try something like this.

new = string.split(':')
for i in range(new):
    if new[i][0] == "\":
        new[i-1] += new.pop(i)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521259

Try splitting on the regex pattern :(?!\\):

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']

The logic is to split on any colon which is not immediately followed by a path separator. This spares the : in the file path from being targeted as a point for splitting.

Upvotes: 6

Related Questions