How to identify a string as being a byte literal?
<p>In Python 3, if I have a string such that:</p>

<pre><code>print(some_str)
</code></pre>

<p>yields something like this:</p>

<pre><code>b'This is the content of my string.\r\n'
</code></pre>

<p>I know it's a byte literal. </p>

<p>Is there a function that can be used to determine if that string is in byte literal format (versus having, say, the Unicode <code>'u'</code> prefix) without first interpreting? Or is there another best practice for handling this? I have a situation wherein getting a byte literal string needs to be dealt with differently than if it's in Unicode. In theory, something like this:</p>

<pre><code>if is_byte_literal(some_str):
    // handle byte literal case
else:
    // handle unicode case
</code></pre>

<p>The easiest and, arguably, best way to do this would be by utilizing the built-in <a href="https://docs.python.org/3/library/functions.html#isinstance"><code>isinstance</code></a> with the <code>bytes</code> type:</p>

<pre><code>some_str = b'hello world'
if isinstance(some_str, bytes):
    print('bytes')
elif isinstance(some_str, str):
    print('str')
else:
    # handle
</code></pre>

<p>Since, a byte literal will <em>always</em> be an instance of <code>bytes</code>, <code>isinstance(some_str, bytes)</code> will, of course, evaluate to <code>True</code>.</p>

python string python-3.x