- 1 year ago
Why is multiline string altered on print or write? (Python 3.6 on Windows)
In Python, multiline strings enclosed within triple quotes ('''
or """
) can contain line breaks and special characters without any alteration. However, when you print or write multiline strings, you might observe differences due to the way Python processes newline characters and platform-specific line endings.
In your case, you mentioned that you are observing differences in behavior on Windows. This is because Windows uses a different line ending convention compared to Unix-like systems (Linux, macOS). Windows uses the combination of two characters: carriage return (\r
) followed by a newline (\n
) to represent a line break, whereas Unix-like systems use just a newline (\n
).
When you print or write a multiline string on Windows, Python may automatically translate the single newline (\n
) in your multiline string to the Windows line ending format (\r\n
). This translation is performed to ensure that the output on Windows systems appears as expected.
For example, consider the following code:
pythonmultiline_string = '''Line 1
Line 2
Line 3'''
print(multiline_string)
On a Unix-like system, the output will be:
mathematicaLine 1
Line 2
Line 3
On a Windows system, the output will be:
mathematicaLine 1
Line 2
Line 3
To maintain consistent behavior across different platforms, Python handles this newline translation automatically. However, if you want to control the line endings explicitly, you can use the io
module's open
function with the newline
parameter:
pythonimport io
with io.open('output.txt', 'w', newline='') as file:
file.write(multiline_string)
Using newline=''
ensures that Python does not perform newline translation, and the line endings in the file will match the ones in your multiline string.
In summary, the alteration you observe in multiline strings when printing or writing on Windows is due to newline translation, which ensures consistent line endings across different platforms. If you need fine-grained control over line endings, you can use the newline
parameter in the io.open
function.