How to escape backslashes in R string

后端 未结 3 1912
误落风尘
误落风尘 2020-11-22 09:56

I\'m writing strings which contain backslashes (\\) to a file:

x1 = "\\\\str"

x2 = "\\\\\\str"
# Error: \'\\s\' is an unreco         


        
3条回答
  •  耶瑟儿~
    2020-11-22 10:41

    [...] If I want to get a string containing 5 \ ,should i write 10 \ [...]

    Yes, you should. To write a single \ in a string, you write it as "\\".

    This is because the \ is a special character, reserved to escape the character that follows it. (Perhaps you recognize \n as newline.) It's also useful if you want to write a string containing a single ". You write it as "\"".

    The reason why \\\str is invalid, is because it's interpreted as \\ (which corresponds to a single \) followed by \s, which is not valid, since "escaped s" has no meaning.

提交回复
热议问题