如何在R字符串中转义反斜杠 [英] How to escape backslashes in R string
问题描述
我正在使用R将文字写入文件:
> x1 =\\str
> x2 =\\\str
错误:'\s'是字符串中无法识别的转义,起始于\\\s
> x2 =\\\\str
>写(file ='test',c(x1,x2))
当我打开名为 test
,我看到:
\str
\\str
如果我想获取一个包含5个反斜杠的字符串,我应该写10个反斜杠,这样吗?
x =\\\\\\\\\\ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ ...] 如果我想得到一个包含5个 \
的字符串,我应该写10个 \
[...]
要在字符串中写入单个 \
,请将其写为\\
。
这是因为 \
是一个特殊字符,保留给转义后面的字符它。 (也许你将 \\\
识别为换行符。)如果要编写一个包含单个
。您将其写为\
。
\\ \\\\str
无效,是因为它被解释为 \\
(对应于单个 \
),后跟 \s
,这是无效的,因为转义 s
没有意义。
I'm writing strings to a file using R:
> x1="\\str"
> x2="\\\str"
Error: '\s' is an unrecognized escape in character string starting "\\\s"
> x2="\\\\str"
> write(file='test',c(x1,x2))
When I open the file named test
, I see this:
\str
\\str
If I want to get a string containing 5 backslashes, should I write 10 backslashes, like this?
x="\\\\\\\\\\str"
解决方案
[...] 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.
这篇关于如何在R字符串中转义反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!