如何避免 R 的 sprintf 中的换行符(“带有换行符的非常长的字符串")?
问题描述:
我在 sprintf()
中有一个很长的字符串.它太长以至于打破它(但仅在源代码中,而不是在输出中)会很有用(可读性).但是每当我打破长字符串时,它都会引入一个 \n
,因此输出也有一个换行符.如何打破源代码中的字符串,使其在输出中不被破坏?
I have a very long string inside sprintf()
. It's so long that it would be useful (readability) to break it (but only in the source code, not in the output). But whenever I break the long string, it introduces a \n
and thus the output has a linebreak as well. How can I break the string in the source code such that it isn't broken in the output?
答
也许以下类似的东西会有用(尽管在不知道输入字符串的实际外观或打算如何使用它们的情况下很难判断).
Perhaps something like the following would be useful (though it's hard to tell without knowing what your input strings actually look like or how you intend to use them).
Fmt <- c(" %s is %d feet tall.\n",
"%s likes chocolate.\n",
"%s eats %d bars of chocolate",
"every night after dinner.")
sprintf(paste(Fmt, collapse = " "), "Sven", 7, "Sven", "He", 3)
# [1] " Sven is 7 feet tall.\n Sven likes chocolate.\n He eats 3 bars of chocolate every night after dinner."
cat(.Last.value)
# Sven is 7 feet tall.
# Sven likes chocolate.
# He eats 3 bars of chocolate every night after dinner.