0

As I was carefully checking a parser script I wrote, I realised that it has done something to the values in some key-value pairs containing double backslash. After a while, realised it was the natural behaviour of print I was seeing, eg:

>>> print("some\\thin")
some\thin

It loses a backslash. When I first wrote the parser, used print so I could see the output and iterate. When it was ready to go, I opened a file at the start of the program, closed it at the end and put a , file=f into every print statement.

Does anyone know how to lightly modify the print command so that it will print both backslashes?

That may be a bit inelegant or dangerous, so I'd be happy to just add something into the for loop otherwise:

strings_list = ["something_normal", "someth\\ing_unusual"]

for string in strings_list:
    if "\\" in string:
        # something needs to go here which prints 
        # a string containing a backslash to the file f
        pass
    else:
        print(string)
cardamom
  • 6,873
  • 11
  • 48
  • 102
  • 1
    `print(r'some\\thin')`. If you want to use a loop see my duplicate below on how to to turn a `str` into a raw string. (i.e. `print(%r" % string)` – Error - Syntactical Remorse Jun 27 '19 at 13:58
  • Thanks, playing around with the raw string, I could come up with a line to go after that `if` statement which makes it work: `print(string.replace("\\", "\\\\"))` – cardamom Jun 27 '19 at 14:10
  • Furthermore, was able to modify the behaviour of `print` inspired by [this](https://stackoverflow.com/a/46658735/4288043) solution. `if "\\" in args[0]:` , `builtins.print(args[0].replace("\\", "\\\\"), **kwargs)` – cardamom Jun 27 '19 at 14:27

0 Answers0