Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a long multi-line string in Python?
In Python, you can create long multi-line strings using several approaches. Each method has its own advantages depending on your specific use case and formatting requirements.
Using Triple Quotes
The most common approach is using triple quotes (''' or """). This method preserves the exact formatting including line breaks, indentation, and special characters like TAB or NEWLINES ?
multiline_string = """Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you"""
print("The multi-line string is:")
print(multiline_string)
The multi-line string is: Welcome to Tutorialspoint How are you doing? Hope everything is fine Thank you
Using Parentheses with String Concatenation
You can wrap multiple strings in parentheses to concatenate them. This approach requires explicit newline characters (\n) where you want line breaks ?
multiline_string = ("Welcome to Tutorialspoint\n"
"How are you doing?\n"
"Hope everything is fine\n"
"Thank you")
print("The multi-line string is:")
print(multiline_string)
The multi-line string is: Welcome to Tutorialspoint How are you doing? Hope everything is fine Thank you
Using Backslash Line Continuation
The backslash (\) character allows you to continue a string literal on the next line. Like the parentheses method, you need explicit \n characters for line breaks ?
multiline_string = "Welcome to Tutorialspoint\n" \
"How are you doing?\n" \
"Hope everything is fine\n" \
"Thank you"
print("The multi-line string is:")
print(multiline_string)
The multi-line string is: Welcome to Tutorialspoint How are you doing? Hope everything is fine Thank you
Comparison
| Method | Preserves Formatting | Best For |
|---|---|---|
| Triple Quotes | Yes | Natural multi-line text, docstrings |
| Parentheses | No (manual \n) | Clean code formatting |
| Backslash | No (manual \n) | Simple string continuation |
Conclusion
Use triple quotes for natural multi-line strings that preserve formatting. Use parentheses or backslash continuation when you need more control over the final string format and code readability.
