# How to handle '\\\\' as a delimiter in Python strings

**URL:** <https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692>\
**Category:** Python Help\
**Created:** [August 31, 2023, 3:11pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692 "2023-08-31T15:11:24Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![hobbycoder](https://avatars.discourse-cdn.com/v4/letter/h/8491ac/32.png) [@hobbycoder](https://discuss.python.org/u/hobbycoder)\
**Post date:** [August 31, 2023, 3:11pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/1 "2023-08-31T15:11:24Z")

</div>

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:

```auto
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 doesn’t:

```auto
def dedupe_and_sort(input_string, delimiter='\\'):
    ''' get a list item that contains a delimited string, dedupe and sort it and pass it back '''
    distinct_items = set(x.strip() for x in input_string.split(delimiter))
    return (delimiter.join(sorted(distinct_items)))

```

What is the correct way to handle the ‘\\’ as a delimiter within the function dedupe\_and\_sort?

---

<div class="post-metadata">

**Author:** ![effigies](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/effigies/32/35835_2.png) [@effigies](https://discuss.python.org/u/effigies)\
**Post date:** [August 31, 2023, 3:18pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/2 "2023-08-31T15:18:27Z")

</div>

What incorrect result do you get? Here’s what I see:

```python
In [1]: def dedupe_and_sort(input_string, delimiter='\\'):
   ...: ''' get a list item that contains a delimited string, dedupe and sort it and pass it bac
   ...: k '''
   ...: distinct_items = set(x.strip() for x in input_string.split(delimiter))
   ...: return (delimiter.join(sorted(distinct_items)))
   ...: 

In [2]: dedupe_and_sort('bananas\\apples\\pears\\apples\\bananas\\pears')
Out[2]: 'apples\\bananas\\pears'

```

---

<div class="post-metadata">

**Author:** ![BowlOfRed](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/bowlofred/32/3379_2.png) [@BowlOfRed](https://discuss.python.org/u/BowlOfRed)\
**Post date:** [August 31, 2023, 4:12pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/3 "2023-08-31T16:12:19Z")

</div>

> [@hobbycoder](#):
>
> 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.

Does the double-backslash already exist in the file? Because the code examples are using a single backslash as a delimiter.

```python
single_backslash = '\\'

```

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [August 31, 2023, 5:22pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/4 "2023-08-31T17:22:16Z")

</div>

> [@hobbycoder](#):
>
> `input_string = 'bananas\\apples\\pears\\apples\\bananas\\pears'`

How many backslashes do you think are _actually in_ this string?

There are five, not ten.

If you actually see `bananas\\apples\\pears\\apples\\bananas\\pears` when you, for example, save the data from the “external data source” to a text file and open it in a text editor, then that source data contains ten backslashes. But the `input_string` you are using to test only uses a single backslash in between each fruit name. If you `.write` it to a text file and open that text file in a text editor, you will only see five backslashes. The `\\` that you type _in the source code_ is special syntax that means a _single_ backslash in the _actual string_. This is because the first `\` has special meaning: it begins an _escape sequence_ that lets you put things into the string that are hard or impossible to type, would mess up the formatting of the code, or would prevent Python from understanding the code (e.g. so that you can put a quote symbol into the string, and Python can know that it’s part of the string instead of the syntax to say where the string ends).

You need to make sure of what the delimiter actually is, in the actual data that you have. The code that you show works fine for the test data that you show.

---

<div class="post-metadata">

**Author:** ![hobbycoder](https://avatars.discourse-cdn.com/v4/letter/h/8491ac/32.png) [@hobbycoder](https://discuss.python.org/u/hobbycoder)\
**Post date:** [August 31, 2023, 6:39pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/5 "2023-08-31T18:39:23Z")

</div>

> [@kknechtel](#):
>
> You need to make sure of what the delimiter actually is, in the actual data that you have. The code that you show works fine for the test data that you show.

in the SQL table there’s basically field stuffing going on and the string literal in the table column would be bananas apples pears apples bananas pears with a double backslash delimiting each. So I’m 100% certain the every delimited record read in from the table has a double backslash in the string as a delimiter between each word where a field has been stuffed with multiple values.

Thus, I’m reading in a column value from a SQL query, it needs to be deduped and sorted and written back with two backslashes, just the way it was retrieved from the table.

Various calls and their results:

 ![image](https://us1.discourse-cdn.com/flex002/uploads/python1/original/2X/9/9bc9662bd899464b268c7e74a953de61d2fe71fc.png)

---

<div class="post-metadata">

**Author:** ![jamestwebber](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jamestwebber/32/12799_2.png) [@jamestwebber](https://discuss.python.org/u/jamestwebber)\
**Post date:** [August 31, 2023, 6:47pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/6 "2023-08-31T18:47:46Z")

</div>

Based on that, it seems like you understand the difference between `"\\\\"` (two backslashes, escaped) and `"\\"` (just one). So where’s the confusion?

In the first example, you are splitting a string with _single_ backslashes, and joining it with doubled ones. So you get the expected output. In the second and third you are splitting and joining with single backslashes.

to clarify more, the string you have defined as `input_string` doesn’t have the doubled backslashes in it. If you print it out you will see that.

---

<div class="post-metadata">

**Author:** ![hobbycoder](https://avatars.discourse-cdn.com/v4/letter/h/8491ac/32.png) [@hobbycoder](https://discuss.python.org/u/hobbycoder)\
**Post date:** [August 31, 2023, 6:53pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/7 "2023-08-31T18:53:29Z")

</div>

> [@jamestwebber](#):
>
> to clarify more, the string you have defined as `input_string` doesn’t have the doubled backslashes in it. If you print it out you will see that.

Of course, silly me getting confused with visual presentation vs underlying content. Thx. In hindsight the answer is pretty obvious, sorry for wasting your time, but appreciate the feedback.

---

<div class="post-metadata">

**Author:** ![jeff5](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jeff5/32/1518_2.png) [@jeff5](https://discuss.python.org/u/jeff5)\
**Post date:** [September 1, 2023, 6:02am UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/8 "2023-09-01T06:02:26Z")

</div>

Surprisingly, no-one has pointed out that [raw-string literals](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) are useful when typing strings in your code that contain backslash (but don’t need to represent special characters like newline). It basically turns off the backslash-escape convention, so the visual confusion is less.

Then the string you get looks more like the string you type. ` r"\\"` is a string of two backslashes. It is commonly used for Windows file paths and regular expressions.

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [September 1, 2023, 9:10pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/9 "2023-09-01T21:10:15Z")

</div>

> [@jeff5](#):
>
> It basically turns off the backslash-escape convention, so the visual confusion is less.

Do keep in mind that raw string literals _do_ still use backslash to prevent a quote that comes immediately after from terminating the string - but they don’t “escape” the quote when doing so. Thus:

```auto
>>> r'\''
"\\'"
>>> print(r'\'')
\'

```

The string contains a backslash and a single-quote. The backslash in the raw string literal syntax allows the `'` to be part of the string, but is still a backslash. This happens because Python considers the backslash **when it tokenizes the code** , to figure out where the string ends; then it determines _what the string actually contains_ **on a later pass** , taking the `r` prefix into account.

For the same reason, a raw string literal **cannot** end with an odd number of backslashes:

> <https://stackoverflow.com/questions/647769/why-cant-pythons-raw-string-literals-end-with-a-single-backslash>

And, of course, the resulting string cannot contain the closing quote character _without also_ having a backslash in front of that quote.

---

<div class="post-metadata">

**Author:** ![flyinghyrax](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/flyinghyrax/32/12394_2.png) [@flyinghyrax](https://discuss.python.org/u/flyinghyrax)\
**Post date:** [September 1, 2023, 10:02pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/10 "2023-09-01T22:02:04Z")

</div>

> [@kknechtel](#):
>
> This happens because Python considers the backslash **when it tokenizes the code** , to figure out where the string ends; then it determines _what the string actually contains_ **on a later pass** , taking the `r` prefix into account.

This explains a lot, thank you! I had a problem with this recently and couldn’t understand what the rules were for backslashes inside raw strings. In my case I ended up doing silly stuff like this:

```python
_esc = “\x5c”

# later…
some_pattern =f”{_esc}”

```

---

<div class="post-metadata">

**Author:** ![hansgeunsmeyer](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/hansgeunsmeyer/32/15188_2.png) [@hansgeunsmeyer](https://discuss.python.org/u/hansgeunsmeyer)\
**Post date:** [September 2, 2023, 12:33pm UTC](https://discuss.python.org/t/how-to-handle-as-a-delimiter-in-python-strings/32692/11 "2023-09-02T12:33:21Z")

</div>

Backslashes can be nasty. You can find a good explanation here:

> **[Backslashes](https://xkcd.com/1638/)**
>
> I searched my .bash\_history for the line with the highest ratio of special characters to regular alphanumeric characters, and the winner was: cat out.txt | grep -o "\[\[(\].\*\[\])\]\[^)\]\]\*$" ... I have no memory of this and no idea what I was trying to do, but I sure hope it worked.
