32

如果我有一个包含换行符的字符串,如何在 R 中对其进行编码而不\n在行之间手动添加,然后用换行符打印它?应该有多行输出;原始字符串的每一行都应作为单独的行打印。

这是一个如何在 Python 中完成任务的示例:

string = """
  Because I could
  Not stop for Death
  He gladly stopped for me
  """

示例用例:我有一个很长的 SQL 代码,其中包含一堆换行符和子命令。我想将代码作为单个字符串输入以供稍后评估,但手动清理它会很困难。

4

1 回答 1

43

没有什么特别的需要。只是开头和结尾的引号。

在 R 中:

x = "Because I could
Not stop for Death
He gladly stopped for me"
x
# [1] "Because I could\nNot stop for Death\nHe gladly stopped for me"

cat(x)
# Because I could
# Not stop for Death
# He gladly stopped for me

在 Python 中:

>>> string = """
...     Because I could
...     Not stop for Death
...     He gladly stopped for me
... """
>>> string
'\n\tBecause I could\n\tNot stop for Death\n\tHe gladly stopped for me\n'
于 2017-10-18T21:01:30.420 回答