简体   繁体   中英

What is the difference between string literals and string values?

See this answer .

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


A string is a Python object representing a text value. 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. 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 , the characters displayed if you print the string:

>>> print(some_string)
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM