Scala Multi-line & Raw Strings
Build multi-line strings and raw strings in Scala for Python Developers—hands-on steps, troubleshooting, and what to study next.
Focus: build multi-line strings and raw strings
You're happily writing Python, using triple quotes for docstrings and raw strings for regex patterns, when suddenly you're asked to port a script to Scala. You reach for """ to create a multi-line string, and it works — but then you hit a backslash that's supposed to stay literal, and your regex breaks. Or you try to embed a newline in a string and wonder why your output looks wrong. This lesson solves exactly that pain: how to build multi-line strings and raw strings in Scala, with the same confidence you have in Python, but using Scala's own idioms — including the stripMargin trick that Python developers envy.
The problem this lesson solves
In Python, you've likely used:
- Triple quotes (""" or ''') for multi-line strings.
- Raw strings (r"...") to avoid escaping backslashes, especially for regex patterns.
When you start writing Scala, you expect similar behavior, but Scala has its own rules. If you don't know them, you'll face confusing errors: your multi-line string includes indentation you didn't want, or your regex pattern contains double backslashes that don't match. This lesson walks you through creating multi-line and raw strings in Scala, so you can write clean, correct code from the start — without the trial-and-error that plagues many newcomers.
By the end, you'll be able to:
- Create multi-line strings using triple quotes, just like in Python, but with added features.
- Use Scala's stripMargin to manage indentation elegantly.
- Define raw strings to keep backslashes literal, essential for regex and file paths.
Core concept / mental model
Think of strings in Scala as a more powerful cousin of Python strings. In Python, a string is a sequence of characters, and you use escapes like \n for newlines and r"" to suppress them. In Scala, you have two main tools:
- Triple-quoted strings (
"""): Multi-line strings that also act as raw strings. Inside them, you don't need to escape backslashes or quotes. This is similar to Python's triple quotes, but with a twist: Scala's triple-quoted strings are automatically raw — norprefix required. stripMargin: A method to remove leading whitespace up to a margin character (default is|). This solves the indentation problem that plagues multi-line strings.
Mental model: Imagine a string as a block of text on a canvas. In Python, you have to carefully position each line. In Scala, you draw the text freely, then use a margin marker to tell the compiler where the text actually starts — like cutting a shape from paper with a guide line.
Key definitions
- Multi-line string: A string that spans multiple lines in source code, preserving newlines.
- Raw string: A string where backslashes are treated literally — no escape sequences.
stripMargin: A function that trims whitespace up to a margin character, often|or another custom character.
How it works step by step
Let's build your understanding step by step.
Step 1: Use triple quotes for multi-line strings
In Scala, you write:
val message = """Hello,
World!"""
println(message)
This prints:
Hello,
World!
No escaping needed for newlines or quotes inside the triple-quoted string. That's a huge win over regular strings.
Step 2: Understand raw string behavior
In triple-quoted strings, backslashes are literal. So:
val regex = """\d{3}-\d{2}-\d{4}"""
println(regex) // Prints: \d{3}-\d{2}-\d{4}
This is exactly what you'd write with Python's r"\d{3}-\d{2}-\d{4}".
Step 3: Handle indentation with stripMargin
Often, you want to format multi-line strings in your code for readability, but you don't want that indentation in the final output. stripMargin fixes this:
val html = """<html>
| <body>
| <h1>Hello</h1>
| </body>
|</html>""".stripMargin
println(html)
Output:
<html>
<body>
<h1>Hello</h1>
</body>
</html>
The | character marks the beginning of each line's content, and everything before it is stripped.
Step 4: Use a custom margin character
If | doesn't suit you, you can specify another character:
val data = """name: John
#age: 30""".stripMargin('#')
println(data)
Output:
name: John
age: 30
This is handy when | might appear in your content.
Hands-on walkthrough
Let's put this into practice with a real exercise: build a small configuration text and a regex pattern, then print them.
Example 1: Create a formatted message
// Multi-line string with stripMargin for clean output
val welcome = """
|====================================
| Welcome to Scala!
| This is a multi-line string demo.
|====================================""".stripMargin
println(welcome)
Output:
====================================
Welcome to Scala!
This is a multi-line string demo.
====================================
Notice the leading newline after """ is preserved — you may need to handle that by starting on the next line or using .stripMargin to remove it.
Example 2: Build a regex pattern as a raw string
// Raw string for regex — no escaping needed
val datePattern = """\d{4}-\d{2}-\d{2}"""
val input = "Today is 2025-04-01"
val regex = datePattern.r
println(regex.findFirstIn(input).getOrElse("No match")) // Prints: 2025-04-01
Output:
2025-04-01
Example 3: Combine multi-line and raw in a practical scenario
// A SQL query as a multi-line raw string
val query = """
|SELECT name, age
|FROM users
|WHERE age > 30
|ORDER BY name""".stripMargin
println(query)
Output:
SELECT name, age
FROM users
WHERE age > 30
ORDER BY name
Pro tip: In Scala, the triple-quoted string is both multi-line and raw — you don't need a separate
rawprefix like in Python. This is a key difference to remember.
Compare options / when to choose what
| Feature | Python | Scala |
|---|---|---|
| Multi-line string | Triple quotes """ |
Triple quotes """ |
| Raw string | Prefix r e.g., r"..." |
Triple quotes automatically raw |
| Escape sequences | Work in regular and triple quotes | Regular strings use escapes; triple quotes don't |
| Indentation control | Manual or textwrap.dedent |
stripMargin with default | |
| Custom margin | Not built-in | stripMargin('c') |
In Python, you often handle indentation with textwrap.dedent; in Scala, stripMargin is idiomatic and built in.
When to choose what:
- For simple multi-line text, triple quotes are enough.
- For formatted output with indentation, use stripMargin.
- For regex patterns or file paths, use triple quotes (raw) to avoid double backslashes.
Troubleshooting & edge cases
Issue: Leading newline appears in output
When you start a triple-quoted string with """\n, the newline is included. To avoid it, either place the content immediately after """ (if on the same line), or use .stripMargin and start with | on the next line. Example:
val noLeadingNewline = """"Hello"""" // This is valid but tricky
Better: Place the opening """ on the same line as the first content if you don't want a leading newline.
Issue: Backslashes are literal — how to insert an escape sequence?
Inside a triple-quoted string, \n is literal backslash-n, not a newline. If you need a newline, you must actually write a newline in the source code, or use string interpolation with \n outside triple quotes.
Issue: stripMargin leaves a trailing margin on the first line
If the first line doesn't start with |, it's not stripped. For example:
val text = """Hello
| World""".stripMargin
The first line remains Hello without stripping, which is usually fine, but be consistent.
Issue: Triple quotes inside triple-quoted strings
To include """ in your string, you need a workaround — often using string concatenation or a different delimiter. For instance:
val withQuotes = """He said """ + "\"\"\"" + """ hi"""
This is rare but good to know.
What you learned & what's next
You've mastered building multi-line strings and raw strings in Scala. You now understand:
- Triple quotes create multi-line strings that are also raw.
- stripMargin handles indentation cleanly.
- You can use custom margin characters when needed.
- Backslashes stay literal in triple quotes, perfect for regex.
This skill is foundational for writing clear, maintainable code — whether you're generating SQL, HTML, or configuration files.
Next lesson in the track: We'll explore string interpolation in Scala, which lets you embed variables directly into strings — a powerful complement to the raw strings you just learned. Keep practicing, and you'll be writing idiomatic Scala in no time.
Practice recap
Write a Scala script that builds a multi-line JSON-like configuration string with indentation using stripMargin, and a regex pattern to extract an email address from a text. Verify the output matches your expectations, and experiment with a custom margin character.
Common mistakes
- Assuming Python's
r"..."exists in Scala — instead, use triple quotes for raw strings. - Forgetting to call
stripMarginand ending up with unwanted indentation in multi-line strings. - Using escape sequences like
\ninside triple-quoted strings, expecting a newline, but getting literal backslash-n. - Including a leading newline unintentionally when string content starts right after the opening triple quotes.
Variations
- Use regular strings with escape sequences for single-line raw behavior, but they require double backslashes.
- Use
stripMarginwith a custom character if|appears in your content. - Combine string interpolation with multi-line raw strings for dynamic content (covered in the next lesson).
Real-world use cases
- Building SQL queries as multi-line strings for readability in database access code.
- Defining complex regex patterns without escaping backslashes, especially for JSON or log parsing.
- Generating HTML templates or email bodies with clean formatting and
stripMargin.
Key takeaways
- Scala's triple-quoted strings create multi-line strings that are automatically raw — no separate
rprefix. - Use
stripMarginto remove indentation from multi-line strings, default margin is|. - Backslashes in triple quotes are literal, so write regex patterns without double escaping.
- Custom margin characters allow flexibility when
|is used in content. - Be mindful of leading newlines — start content on the same line or manage them with
stripMargin.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.