You have the right idea with escaping the backslashes, but despite how it looks, your input string doesn't actually have any backslashes in it. You need to escape them in the input, too!

>>> a = "1\\2\\3\\4"  # Note the doubled backslashes here!
>>> print(a.split('\\'))  # Split on '\\'
['1', '2', '3', '4']

You could also use a raw string literal for the input, if it's likely to have many backslashes. This notation is much cleaner to look at (IMO), but it does have some limitations: read the docs!

>>> a = r"1\2\3\4"
>>> print(a.split('\\'))
['1', '2', '3', '4']

If you're getting a elsewhere, and a.split('\\') doesn't appropriately split on the visible backslashes, that means you've got something else in there instead of real backslashes. Try print(repr(a)) to see what the "literal" string actually looks like.

>>> a = '1\2\3\4'
>>> print(a)
1☻♥♦
>>> print(repr(a))
'1\x02\x03\x04'

>>> b = '1\\2\\3\\4'
>>> print(b)
1\2\3\4
>>> print(repr(b))
'1\\2\\3\\4'
Answer from Henry Keiter on Stack Overflow
🌐
Narkive
tutor.python.narkive.com › P9VY5XNY › using-split-with-a-backslash
[Tutor] Using split with a backslash
Try the below, notice the string prefix r and that the backslash is now escaped by another backslash. ... LeafJawPositions=r'-42.000000000001\29.800000000001' LeafJawPositions '-42.000000000001\\29.800000000001' ... x1, x2 = LeafJawPositions.split('\\') x1, x2 ('-42.000000000001', '29.800000000001') See http://docs.python.org/ref/strings.html for more info.
🌐
Quora
quora.com › How-do-you-backslash-a-string-in-Python
How to backslash a string in Python - Quora
Depends on what you want to use to split the string: (1) a character position? Use Mystr[0:x] and MyStr [x:] ... Note: MyRE is not surrounded by “/”s. ... In Python, why can't the raw string end in a backslash since all backslashes are left in the raw string?
🌐
GoPa
faun.dev › c › stories › thenjikubheka › string-manipulation-in-python-a-comprehensive-guide
String Manipulation in Python: A Comprehensive Guide
January 18, 2022 - We will evaluate Python functions and methods that allow you to manipulate strings. ... These are characters in Python represented with backslash (\).
Top answer
1 of 2
2

I think you're trying harder than you need to. Python has an os module which has a function to do exactly what you want, independent of platform. Here, you just need to use

fileName=os.path.basename(targetDirectory)

Also, if you're using Python you should seriously consider moving away from camel case (fileName) to the more Pythonic snake case (file_name).

2 of 2
2

A small example,

>>> print s
this/hello\
>>> import re
>>> re.split('/',s)
['this', 'hello\\']
>>> re.split('\\',s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 171, in split
    return _compile(pattern, flags).split(string, maxsplit)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)
>>> re.split(r'\\',s)
['this/hello', '']

'r' prefix matters!

Reference!

That is,

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. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase "n". String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.

🌐
CSDN
devpress.csdn.net › python › 63045415c67703293080b37c.html
Split a string by backslash in python_python_Mangs-Python
You could also use a raw string literal for the input, if it's likely to have many backslashes. This notation is much cleaner to look at (IMO), but it does have some limitations: read the docs! >>> a = r"1\2\3\4" >>> print(a.split('\\')) ['1', '2', '3', '4']
Find elsewhere
🌐
YouTube
youtube.com › watch
PYTHON : Split a string by backslash in python
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
YouTube
youtube.com › watch
How to Properly Split Strings with a Backslash in Python - YouTube
Learn how to split strings in Python that contain backslashes. Understand the correct usage of escape characters and raw strings for effective string manipul...
Published   April 16, 2025
Views   0
🌐
Python.org
discuss.python.org › python help
How to handle '\\' as a delimiter in Python strings - Python Help - Discussions on Python.org
August 31, 2023 - I am having to load and handle strings from an external data source that are delimited by double backslash. I need to return the sorted and de-duplicated delimited string e.g. input_string = ‘bananas\\apples\\pears\\apples\\bananas\\pears’ the return string should be: ‘apples\\bananas\\pears’ This works: input_string = 'bananas\\apples\\pears\\apples\\bananas\\pears' distinct_items = set(x.strip() for x in input_string.split('\\')) print('\\'.join(sorted(distinct_items))) but this doe...
🌐
Python
mail.python.org › pipermail › tutor › 2008-April › 061023.html
[Tutor] Using split with a backslash
April 2, 2008 - Example: x1, x2 = LeafJawPositions.split('\\') See http://docs.python.org/ref/strings.html Another example: In [1]: a = 'abc\\def\\ghi' In [2]: len(a) Out[2]: 11 In [3]: a.split('\') ------------------------------------------------------------ File "<ipython console>", line 1 a.split('\') ^ SyntaxError: EOL while scanning single-quoted string In [4]: a.split('\\') Out[4]: ['abc', 'def', 'ghi'] - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman · Previous message: [Tutor] Using split with a backslash · Next message: [Tutor] Using split with a backslash · Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
🌐
YouTube
youtube.com › codelift
python split backslash - YouTube
Instantly Download or Run the code at https://codegive.com in python, the backslash ("") is an escape character commonly used in strings. when dealing with ...
Published   February 23, 2024
Views   15
🌐
Pythonmana
pythonmana.com › 2021 › 07 › 20210728124957458l.html
In Python re module, how to use backslash "\" to split strings? - Python知识
July 28, 2021 - The sample code is as follows : ... import sys # backslash escape enter = "\r\n" if sys.platform == "win32" else "\n" # backslash liberal backslash_liberal = "\\" ... here , If you use Python Character split Method , Use two backslashes as separators , There is no problem .
🌐
Python.org
discuss.python.org › python help
Problem with split() command - Python Help - Discussions on Python.org
April 3, 2023 - I have run below statement </> x = ‘d:\level1\test.exe’ print(x.isspace()) result = x.split(‘\’) for i in result: print(i) </> and expected the come out is: False d: level1 test.exe but finally the come out …
🌐
Nabble
python.6.x6.nabble.com › Using-split-with-a-backslash-td1715911.html
Python - tutor - Using split with a backslash
April 2, 2008 - Python › General › Python - tutor · Using split with a backslash · ‹ Previous Topic Next Topic › · Locked 7 messages · bfodness · Reply | Threaded · Open this post in threaded view · Dave Kuhlman
🌐
GitHub
github.com › tensorflow › tensorflow › issues › 26021
SplitPath should split on both forward slashes and backslashes on Windows · Issue #26021 · tensorflow/tensorflow
February 22, 2019 - The whole situation is a bit less clean than one might hope, because the TF filesystem API prefers to use /-separators everywhere while people in Python-land prefer to use os.path.join to insert the proper platform-specific path separator. But it seems clear that the current behavior, where the delimiter used depends on what characters are in the string, is undesirable, and that being consistent with native APIs is a better choice.
Author   tensorflow
🌐
SitePoint
sitepoint.com › get started
Split on a back slash (\\) - Get Started - SitePoint Forums | Web Development & Design Community
September 21, 2007 - String filePath = "c:\\\\documents and settings\\\\you\\\\desktop"; String[] fileParts = filePath.split("\\\\");