>>> var = "C:\\level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8"
>>> var.split('\\', 7)
['C:', 'level1', 'level2', 'level3', 'level4', 'level5', 'level6', 'level7\\level8']
>>> var.split('\\', 7)[-1]
'level7\\level8'
I don't get the same output as you with your code. It could be because I'm on OSX and that isn't recognized as a file path. Regardless, this solution is a bit simpler and gives you the bit you want.
The second parameter tells split the max number of times to split counting from left, so:
>>> var.split('\\', 1)
['C:', 'level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8']
>>> var.split('\\', 2)
['C:', 'level1', 'level2\\level3\\level4\\level5\\level6\\level7\\level8']
# and so on...
You don't need to do anything to remove the extra '\'
, it's there to escape the one you want. You can see this by using print()
:
>>> print(var.split('\\', 7)[-1])
level7\level8