Search code examples
rstringnewlineline-breaksformatted-text

How to code and print a character string formatted with line breaks?


If I have a string that contains line breaks, how can I code it in R without manually adding \n between lines and then print it with the line breaks? There should be multiple lines of output; each line of the original string should print as a separate line.

This is an example of how to do the task in Python:

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

Example use case: I have a long SQL code with a bunch of line breaks and sub-commands. I want to enter the code as a single string to be evaluated later, but cleaning it up by hand would be difficult.


Solution

  • Nothing special is needed. Just a quote mark at the beginning and end.

    In 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
    

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