Search code examples
pythonjuliabackslashstring-literals

How to replace string literals back/front slashes in Julia?


In Python, I can do string replacements of slashes as such:

>>> s = 'ab\c'
>>> s.replace('\\', '\\\\')
'ab\\\\c'
>>> print s.replace('\\', '\\\\')
ab\\c

In Julia, when I could do this:

julia> s = "ab\\c"
"ab\\c"

julia> replace(s, "\\\\", "\\\\\\\\")
"ab\\c"

I've tried this but it throws some syntax error:

julia> replace(s, r"\", r"\\")
ERROR: syntax: "\" is not a unary operator

Solution

  • Julia REPL outputs strings in escaped form. It might be best to wrap things with a println as in println(replace(s, "\\", "\\\\")). In this case you get:

    julia> s = "ab\\c"
    "ab\\c"
    
    julia> println(s)
    ab\c
    
    julia> println(replace(s, "\\", "\\\\"))
    ab\\c
    

    Regarding the use of regular expressions, the first r"\" is a partial regular expression and the parser continue and generates an error on the following \ after a closing ", and the second regexp is unnecessary as it is the string to be inserted.

    UPDATE: More details about Julia vs. Python escaping in the other answer.

    Hope this helps!