【问题标题】:How can a string object be built from a string literal?如何从字符串文字构建字符串对象?
【发布时间】:2020-05-24 07:01:35
【问题描述】:

看到这个answer

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

我真的不明白,如何从字符串字面量构建字符串对象?

'''
multiline
content
'''

另外,上面的字符串文字如何?请帮我理解字符串文字和字符串对象之间的区别?

【问题讨论】:

    标签: python string object string-literals


    【解决方案1】:

    请参阅Literals 上的 python 文档:

    文字是某些内置类型的常量值的表示法。

    字符串文字是存在于源代码中的东西——它是一种写入字符串值的方式。字符串对象是str 对象的内存表示。您可以将其与整数文字进行比较,例如 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
    

    如果需要,您可以做一些further reading

    在计算机科学中,字面量是在源代码中表示固定值的符号。 ... 字面量常用于初始化变量,...

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 2015-09-08
      相关资源
      最近更新 更多