This is documentation for Mathematica 4, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
Wolfram Research, Inc.

Special CharactersAdvanced Topic: Character Codes

2.7.6 Advanced Topic: Newlines and Tabs in Strings

Explicit representations of newlines and tabs in strings.

This prints on two lines.

In[1]:= "First line.\nSecond line."


In InputForm there is an explicit \n to represent the newline.

In[2]:= InputForm[%]

Out[2]//InputForm= "First line.\nSecond line."

When you enter a long string in Mathematica, it is often convenient to break your input across several lines. Mathematica will by default ignore such breaks, so that if you subsequently output the string, it can then be broken in whatever way is appropriate.

Mathematica ignores the line break and any tabs that follow it.

In[3]:= "A string on

two lines."


There is no newline in the string.

In[4]:= InputForm[%]

Out[4]//InputForm= "A string on two lines."

Input forms for strings.

Now Mathematica keeps the newline.

In[5]:= "\<A string on

two lines.\>"


In InputForm, the newline is shown as an explicit \n.

In[6]:= InputForm[%]

Out[6]//InputForm= "A string on\ntwo lines."

You should realize that even though it is possible to achieve some formatting of Mathematica output by creating strings which contain raw tabs and newlines, this is rarely a good idea. Typically a much better approach is to use the higher-level Mathematica formatting primitives to be discussed in the next two sections. These primitives will always yield consistent output, independent of such issues as the positions of tab settings on a particular device.

In strings with newlines, text is always aligned on the left.

In[7]:= {"Here is\na string\non several lines.",

"Here is\nanother"}


The ColumnForm formatting primitive gives more control. Here text is aligned on the right.

In[8]:= ColumnForm[{"First line", "Second", "Third"}, Right]


And here the text is centered.

In[9]:= ColumnForm[{"First line", "Second", "Third"}, Center]


Within Mathematica you can use formatting primitives to avoid raw tabs and newlines. But if you intend to send your output in textual form to external programs, then these programs will often expect to get raw tabs and newlines.

Note that you must either use WriteString or give your output in OutputForm in order for the raw tabs and newlines to show up. In InputForm, they will just be given as \t and \n.

This outputs a string to a file.

In[10]:= "First line.\nSecond line." >> test

Here are the contents of the file. By default, >> generates output in InputForm.

In[11]:= !!test

""First line.\nSecond line.""

This explicitly tells Mathematica to use OutputForm for the output.

In[12]:= OutputForm["First line.\nSecond line."] >> test

Now there is a raw newline in the file.

In[13]:= !!test

"First line.

Second line."

Special CharactersAdvanced Topic: Character Codes