Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Correctly Write a Raw Multiline String in Python: Essential Tips

#1
How to Correctly Write a Raw Multiline String in Python: Essential Tips

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1246567&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
<p>Python provides an effective way of handling <a href="https://blog.finxter.com/proper-indentation-for-python-multiline-strings/" data-type="post" data-id="51993" target="_blank" rel="noreferrer noopener">multiline strings</a>, which you might have encountered when working with lengthy text or dealing with code that spans multiple lines. Understanding how to correctly write a raw multiline string in Python can be essential for maintaining well-structured and easily readable code.</p>
<p>Ordinarily, we express strings in Python using <strong>single or double quotes</strong>. </p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-strings-made-easy/" data-type="post" data-id="1234117" target="_blank" rel="noreferrer noopener">Python Strings Made Easy</a></p>
<p>However, when it comes to multiline strings, Python offers a special syntax for defining these types of text. To create a multiline string, you can use triple quotes, either single or double, at the beginning and end of your string.</p>
<p class="has-global-color-8-background-color has-background"><strong>To correctly write a raw multiline string in Python, use the letter “r” before your opening triple quotes while enclosing your string with triple quotes. For example: <code>r'''This is a raw\n Multiline String'''</code></strong>. </p>
<p>This denotes a <a href="https://blog.finxter.com/python-raw-strings-a-helpful-easy-guide/" data-type="post" data-id="1246445" target="_blank" rel="noreferrer noopener">raw string</a> and preserves special characters such as <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-escape-special-characters-of-a-python-string-with-a-single-backslash/" data-type="post" data-id="26885" target="_blank">backslashes</a> (used for escape sequences) without interpreting them as part of the string. Doing so lets you easily and efficiently handle long strings spanning multiple lines in your Python code.</p>
<h2>Understanding Raw Strings</h2>
<p>In Python, raw strings are a convenient way to represent strings literally, without processing <a rel="noreferrer noopener" href="https://blog.finxter.com/python-escape-characters/" data-type="post" data-id="34564" target="_blank">escape characters</a>. This can be particularly useful when working with regular expressions or dealing with file system paths. To create a raw string, simply prefix the string literal with an <code>r</code> or <code>R</code> character.</p>
<p>For example, a regular string containing a backslash (such as in a file path) would need to be escaped:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">normal_string = 'C:\\Users\\John\\Documents'
</pre>
<p>With raw strings, you don’t need to escape the backslashes:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">raw_string = r'C:\Users\John\Documents'
</pre>
<p>Both of these variables will hold the same string value.</p>
<p>When it comes to creating raw multiline strings, you can use triple quotes <code>"""</code> or <code>'''</code> combined with the raw string prefix to achieve the desired result. Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">raw_multiline_string = r"""This is a
raw multiline string
with backslashes \t and \n
that are not escaped."""
</pre>
<p>This string will preserve the backslashes and newlines as they appear between the triple quotes.</p>
<p>It is important to note that raw strings cannot end with an odd number of backslashes, as the final backslash would escape the final quote character:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># This will raise a SyntaxError
invalid_raw_string = r"This is not valid\"
</pre>
<p>To deal with this limitation, you can concatenate a regular string with the final backslash:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">valid_raw_string = r"This is valid" + "\\"
</pre>
<h2>Multiline Strings</h2>
<p>In Python, multiline strings are created using triple quotes, either three single quotes (<code>'''</code>) or three double quotes (<code>"""</code>). This allows you to include quotes, tabs, and newlines within the string without using escape characters. Here is an example of a multiline string:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">multiline_string = """This is a
multiline string in Python
with newlines, tabs, and "quotes"."""
</pre>
<p>If you want to create a raw multiline string, you’ll need to use a different approach, as the <code>r</code> prefix only works for single-line strings. One way to achieve this is by combining raw strings and parentheses, adding an <code>r</code> prefix to each part of the string. This will preserve the string’s escape characters:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">raw_multiline_string = (r"on\e" r"\\tw\\o")
</pre>
<p>Keep in mind that when using parentheses, the line break will not be included in the string. You can manually add a line break using the <code>\n</code> escape character in the appropriate location like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">raw_multiline_string_with_linebreak = (r"on\e" r"\n" r"\\tw\\o")
</pre>
<p>This method allows you to create raw multiline strings while preserving the escape characters and maintaining readability in your Python code. </p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Remember</strong>: it’s essential to use the <code>r</code> prefix for each part of the string to ensure it’s treated as a raw string. For more information, check out the discussion on <a href="https://stackoverflow.com/questions/46003452/how-to-correctly-write-a-raw-multiline-string-in-python">Stack Overflow</a>.</p>
<h2>3 Ways to Combine Raw and Multiline Strings</h2>
<p>In Python, you can combine raw and multiline strings to create a string that spans across multiple lines, while also preserving special characters and escape sequences. This section will explain different ways to achieve this combination.</p>
<p>One common approach is to use triple quotes for creating a multiline string. By using three single quotes (<code>'''</code>) or three double quotes (<code>"""</code>), you can create a multiline string that retains any whitespace and can include special characters. To add a raw string, use the <code>r</code> prefix before the triple quotes:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">raw_multiline_string = r"""This is a raw
multiline string with a backslash: \\
and a new line \n is just character literals."""
</pre>
<p>Another way to write a raw multiline string is by using parentheses and string concatenation. Each line of the string can be enclosed in single or double quotes, followed by a space to ensure a single whitespace character divides them. Add the <code>r</code> prefix before each quoted line to maintain the raw string format:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">raw_multiline_string = (r"This is a raw" r" multiline string with a backslash: \\" r" and a new line \n is just character literals.")
</pre>
<p>Alternatively, you can use the <code>+</code> operator to concatenate multiple raw strings, creating a multiline string. This approach allows you to explicitly specify newline characters or other special characters as needed:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">raw_multiline_string = (r"This is a raw" + "\n" r" multiline string with a backslash: \\" + "\n" r" and a new line \n is just character literals.")
</pre>
<p>With these techniques, you can create raw multiline strings that are easier to read and maintain in your Python code.</p>
<h2>Multiline Raw String Use Cases and Examples</h2>
<p>This section reviews some use cases and examples demonstrating <strong>how to correctly write a raw multiline string</strong> in Python.</p>
<p>Using raw multiline strings is beneficial when dealing with strings containing many backslashes or with regular expressions. In these scenarios, raw strings prevent the need to escape backslashes, making the code more readable.</p>
<p>Here’s a basic example of creating a raw multiline string:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">multiline_raw_string = r"""This is a raw \
multiline string in Python. \\
You don't need to escape the backslashes \\."""
</pre>
<p>In this example, the backslashes are preserved in the text as they’re written, without the need to escape them, thanks to the <code>r</code> prefix before the triple quotes.</p>
<p>Now, let’s take a look at a specific use case with <a href="https://blog.finxter.com/python-regex/" data-type="post" data-id="6210" target="_blank" rel="noreferrer noopener">regular expressions</a>:</p>
<p>Suppose you want to match a file path pattern in a text, using a regular expression. Without raw strings, you’d need to escape the backslashes:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re pattern = 'C:\\\\Users\\\\[A-Za-z0-9]+\\\\Documents'
text = 'C:\\Users\\JohnDoe\\Documents\\example.txt' result = re.search(pattern, text)
print(result.group())
</pre>
<p>With raw strings, the regex pattern becomes more readable, as you don’t need to escape the backslashes:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re pattern = r'C:\\Users\\[A-Za-z0-9]+\\Documents'
text = 'C:\\Users\\JohnDoe\\Documents\\example.txt' result = re.search(pattern, text)
print(result.group())
</pre>
<p>In both examples, the output is the same:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">C:\Users\JohnDoe\Documents
</pre>
<p>These examples demonstrate the benefits of using raw multiline strings in Python, especially when working with text that contains special characters like backslashes or incorporating regular expressions in your code.</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<p>Feel free to check out our full guide on raw strings here:</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Full Guide</strong>: <a href="https://blog.finxter.com/python-raw-strings-a-helpful-easy-guide/" data-type="post" data-id="1246445" target="_blank" rel="noreferrer noopener">Python Raw Strings: A Helpful Easy Guide</a></p>
<p>If you want to keep improving your programming skills, consider joining our free email academy (130,000 coders) by downloading your cheat sheets here:</p>
</div>


https://www.sickgaming.net/blog/2023/03/...tial-tips/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016