[英]What is the difference between string literals and string values?
I think your confusion is that you're mixing up the concept of string literals in source code with actual string values.我认为您的困惑是您将源代码中字符串文字的概念与实际字符串值混为一谈。
What is the difference between string literals and string values?字符串文字和字符串值有什么区别? I did not understand this.我不明白这一点。
A string literal is a piece of text you can write in your program's source code, beginning and ending with quotation marks, that tells Python to create a string with certain contents.字符串文字是您可以在程序源代码中编写的一段文本,以引号开头和结尾,告诉 Python 创建具有特定内容的字符串。 It looks like看起来像
'asdf'
or或者
'''
multiline
content
'''
or或者
'the thing at the end of this one is a line break\n'
In a string literal (except for raw string literals), special sequences of characters known as escape sequences in the string literal are replaced with different characters in the actual string.在字符串文字中(原始字符串文字除外),字符串文字中称为转义序列的特殊字符序列将替换为实际字符串中的不同字符。 For example, the escape sequence \n
in a string literal is replaced with a line feed character in the actual string.例如,字符串文字中的转义序列\n
将替换为实际字符串中的换行符。 Escape sequences begin with a backslash.转义序列以反斜杠开头。
A string is a Python object representing a text value.字符串是表示文本值的 Python object。 It can be built from a string literal, or it could be read from a file, or it could originate from many other sources.它可以从字符串文字构建,也可以从文件中读取,也可以源自许多其他来源。
Backslashes in a string have no special meaning, and backslashes in most possible sources of strings have no special meaning either.字符串中的反斜杠没有特殊含义,大多数可能的字符串来源中的反斜杠也没有特殊含义。 For example, if you have a file with backslashes in it, looking like this:例如,如果您有一个包含反斜杠的文件,如下所示:
asdf\n
and you do你也是
with open('that_file.txt') as f:
text = f.read()
the \n
in the file will not be replaced by a line break.文件中的\n
不会被换行符替换。 Backslashes are special in string literals, but not in most other contexts.反斜杠在字符串文字中是特殊的,但在大多数其他上下文中不是。
When you ask for the repr
representation of a string, either by calling repr
or by displaying the string interactively:当您通过调用repr
或以交互方式显示字符串来请求字符串的repr
表示时:
>>> some_string = "asdf"
>>> some_string
'asdf'
Python will build a new string whose contents are a string literal that would evaluate to the original string. Python 将构建一个新字符串,其内容是一个字符串文字,可以评估为原始字符串。 In this example, some_string
does not have '
or "
characters in it. The contents of the string are the four characters asdf
, the characters displayed if you print
the string:在此示例中, some_string
中没有'
或"
字符。字符串的内容是四个字符asdf
,如果您print
字符串,则显示的字符:
>>> print(some_string)
asdf
However, the repr
representation has '
characters in it, because 'asdf'
is a string literal that would evaluate to the string.但是, repr
表示中有'
字符,因为'asdf'
是一个字符串文字,可以计算为字符串。 Note that 'asdf'
is not the same string literal as the "asdf"
we originally used - many different string literals can evaluate to equal strings.请注意, 'asdf'
与我们最初使用的"asdf"
不是同一个字符串文字 - 许多不同的字符串文字可以评估为相等的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.