<p>Python中实际上只有两种类型的字符串(或类似字符串的对象)。在</p>
<p>第一个是“Unicode”字符串,它是一个字符序列。
第二个是字节(或'bytestrings'),它是一个字节序列。在</p>
<p>第一种是Unicode规范中的一系列字母字符。
第二种是0到255之间的一系列整数,通常使用一些假定的编码(如ASCII或UTF-8)呈现为文本(这是在bytestream中编码Unicode字符的规范)。在</p>
<p>在python2中,默认的<code>"my string"</code>是bytestring。
前缀“u”表示“Unicode”字符串,例如<code>u"my string"</code>。在</p>
<p>在python3中,'Unicode'字符串成为默认值,因此<code>"my string"</code>相当于<code>u"my string"</code>。
要获得旧的python2 bytestrings,需要使用前缀b“mystring”(在python3的最旧版本中没有)。在</p>
<p>还有两个前缀,但它们不影响string对象的类型,只影响它的解释方式。
第一个是不解释转义字符(如\n或\t)的“raw”字符串。例如,原始字符串<code>r"my_string\n"</code>包含字面反斜杠和“n”字符,而<code>"my_string\n"</code>在行尾包含一个换行符。在</p>
<p>第二个是在python3的最新版本中引入的:带前缀“f”的格式化字符串。其中,大括号用于显示要解释的表达式。例如,字符串:</p>
<pre><code>my_object = 'avocado'
f"my {0.5 + 1.0, my_object} string"`
</code></pre>
<p>将被解释为<code>"my (1.5, avocado) string"</code>(其中逗号创建了一个元组)。当代码被读取时,这种解释会立即发生;随后字符串没有什么特别的地方。在</p>
<p>最后,您可以使用多行字符串表示法:</p>
^{pr2}$
<p>根据需要使用“r”或“f”说明符。在</p>
<p>在Python2中,如果没有使用前缀或只使用了“r”前缀,则它是bytestring;如果使用了“u”前缀,则它是Unicode字符串。在</p>
<p>在python3中,如果没有使用前缀,或者只使用了“r”、“f”和“u”的组合,则它是Unicode字符串。如果您使用了'b'前缀,那么它是一个bytestring。显然不允许同时使用“b”和“u”。在</p>