代码之家  ›  专栏  ›  技术社区  ›  mmyoung77

如何编码和打印用换行符格式化的字符串?

  •  34
  • mmyoung77  · 技术社区  · 7 年前

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

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

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

    1 回复  |  直到 3 年前
        1
  •  44
  •   Gregor Thomas    7 年前

    不需要什么特别的东西。在开头和结尾只加一个引号。

    在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'