0

Hi I have a string as below

a = 'h\\\\\\elllo'

and I want to replace all backslashes('\') in the string with asterisk('*'). I tried doing something like this

>>> import re
>>> regex = re.compile(r"\\")
>>> re.sub(regex, '*', a)

and I get

'h***elllo'

I want six backslashes to be replaced by six asterisks. Why is that not happening in this case and how do I do that ?

Thank you.

  • That question marked as duplicate is not at all what this question is asking about... Have you tried a single slash in the regex pattern? – dvo Mar 05 '20 at 13:37
  • I tried single slash in the pattern I get an error saying `SyntaxError: EOL while scanning string literal` – Raghavendra Sugeeth Mar 05 '20 at 13:39
  • There are no 6 backslashes, only 3, in `"...\\\\\\..."`. Six backslashes are in `r"....\\\\\\...."`. See [the Python demo](https://ideone.com/IijD7O). – Wiktor Stribiżew Mar 05 '20 at 13:39
  • @RaghavendraSugeeth If you print your `a` variable with no regex replace, are there 3 slashes or 6? It's been a while since I wrote any python, but when you declare `a`, the 6 backslashes are probably really 3 escaped slashes. – dvo Mar 05 '20 at 13:41
  • I want all backslashes to be replaced by all asterisks I want something like this `h******elllo` . It is not just with the asterisk even if I do `re.sub(regex, 'i', a)` I still am getting only `hiiielllo` but I want six 'i' in the resultant string. – Raghavendra Sugeeth Mar 05 '20 at 13:41
  • Was closed (incorrectly) before I could write an answer explaining properly, but just do `re.sub(r"\\", '*',a.replace("\\","\\\\"))` that gives you what you. – KJTHoward Mar 05 '20 at 13:43
  • @RaghavendraSugeeth You can't unless you want to replace a single **literal ``\``** with *two* `*`s. Then you just need `a.replace('\\', '**')`. Again, note `'\\'` is a ``\`` literal string. – Wiktor Stribiżew Mar 05 '20 at 13:43
  • When I print `a` this is what I get `'h\\\\\\elllo'` @dvo – Raghavendra Sugeeth Mar 05 '20 at 13:44
  • @RaghavendraSugeeth And that `'h\\\\\\elllo'` is actually `h\\\elllo` literal text. You are not printing `a`, you just type `a` and hit ENTER. Try `print(a)` instead – Wiktor Stribiżew Mar 05 '20 at 13:45
  • @WiktorStribiżew yes printing a gives me what you told. – Raghavendra Sugeeth Mar 05 '20 at 13:48
  • 2
    So, as I say, it is a duplicate. It is a very common misunderstanding that is not even regex related, you need to study [*Python string literals*](https://docs.python.org/3/reference/lexical_analysis.html#literals). Consider doing it before you go on with coding, these are basics. – Wiktor Stribiżew Mar 05 '20 at 13:50

0 Answers0