How to code and print a character string formatted with line breaks?
16,570
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'
Author by
mmyoung77
Statistician by day - mainly R (including Shiny), but some Python as well. Nerd by night.
Updated on August 08, 2022Comments
-
mmyoung77 almost 2 years
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.
-
mmyoung77 over 6 yearsBetween this, and Michal Stolarczyk's comment above, consider this question answered. Thanks!