字符串文字和字符串值之间有什么区别?

See this answer.

我认为您的困惑是,您要将源代码中的字符串文字与实际的字符串值混合在一起。

字符串文字和字符串值之间有什么区别?我不明白这一点。

评论
  • 陌路人
    陌路人 回复

    字符串文字是您可以在程序的源代码中编写的一段文本,以引号开头和结尾,并告诉Python创建具有某些内容的字符串。看起来像

    'asdf'
    

    要么

    '''
    multiline
    content
    '''
    

    要么

    '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. Escape sequences begin with a backslash.

    字符串是表示文本值的Python对象。它可以从字符串文字中构建,或者可以从文件中读取,或者可以源自许多其他来源。

    字符串中的反斜杠没有特殊含义,大多数可能的字符串源中的反斜杠也没有特殊含义。例如,如果您有一个带有反斜杠的文件,则如下所示:

    asdf\n
    

    你也是

    with open('that_file.txt') as f:
        text = f.read()
    

    the \n in the file will not be replaced by a line break. 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:

    >>> 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. In this example, some_string does not have ' or " characters in it. The contents of the string are the four characters asdf. However, the repr representation has ' characters in it, because 'asdf' is a string literal that would evaluate to the string. Note that 'asdf' is not the same string literal as the "asdf" we originally used - many different string literals can evaluate to equal strings.