Search code examples
pythonstringobjectstring-literals

How can a string object be built from a string literal?


See this answer.

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.

I really did not understand, how can a string object be built from a string literal?

'''
multiline
content
'''

Also, how is the above a string literal? Please help me to understand the difference between string literals and string objects?


Solution

  • See the python documentation on Literals:

    Literals are notations for constant values of some built-in types.

    A string literal is something that exists in source code - it's a way of writing the value of a string. A string object is the in-memory representation of a str object. You can compare this to an integer literal, like 5:

    x = 5  # x is assigned an integer value, using the literal `5`
    y = x + x  # x is assigned a value
    # Both are `int` objects
    print(isinstance(x, int))  # True
    print(isinstance(x, int))  # True
    
    foo = "hello"  # foo is assigned a str value, using the literal `"hello"`
    bar = foo.upper()   # bar is assigned a `str` value
    # Both are `str` objects
    print(isinstance(foo, str))  # True
    print(isinstance(bar, str))  # True
    

    You can do some further reading, if desired:

    In computer science, a literal is a notation for representing a fixed value in source code. ... Literals are often used to initialize variables, ...