Python 简明教程

Python - Literals

What are Python Literals?

Python 字面量或常量是表示源代码中的固定值的符号。与 variables 相反,字面量(123、4.3、“您好”)是静态值,您也可以说它们是常量,在整个程序或应用程序的操作过程中不会发生变化。例如,在以下分配语句中。

Python literals or constants are the notation for representing a fixed value in source code. In contrast to variables, literals (123, 4.3, "Hello") are static values or you can say constants which do not change throughout the operation of the program or application. For example, in the following assignment statement.

x = 10

此处,10 是一个字面量,表示数值 10,它被直接存储在内存中。然而,

Here 10 is a literal as numeric value representing 10, which is directly stored in memory. However,

y = x*2

在此处,即使表达式结果为 20,但它也不会被明确包括在源代码中。您还可以使用内置的 int() 函数来声明一个 int 对象。但是,这也是一种间接的实例化方式,而不是字面量方式。

Here, even if the expression evaluates to 20, it is not literally included in source code. You can also declare an int object with built-in int() function. However, this is also an indirect way of instantiation and not with literal.

x = int(10)

Different Types of Python Literals

Python 提供以下字面量,它们将在本教程中进行说明:

Python provides following literals which will be explained this tutorial:

Python Integer Literal

只包含数字符号(0 到 9)的任何表示都创建了一个 int 类型的对象。这样声明的对象可以使用赋值运算符来引用变量。

Any representation involving only the digit symbols (0 to 9) creates an object of int type. The object so declared may be referred by a variable using an assignment operator.

整数文字包含三种不同类型的文字值:十进制、八进制和十六进制文字。

Integer literals consist three different types of different literal values decimal, octal, and hexadecimal literals.

1. Decimal Literal

十进制文字表示带或不带符号的数字。0 到 9 的数字用于创建十进制文字值。

Decimal literals represent the signed or unsigned numbers. Digitals from 0 to 9 are used to create a decimal literal value.

查看下面将十进制文字赋值给变量的语句:

Look at the below statement assigning decimal literal to the variable −

x = 10
y = -25
z = 0

2. Octal Literal

Python 允许将整数表示为八进制数或十六进制数。在 Python 中,前缀为 0o 或 0O 的仅包含八个数字符号(0 到 7)的数字表示是八进制数。

Python allows an integer to be represented as an octal number or a hexadecimal number. A numeric representation with only eight digit symbols (0 to 7) but prefixed by 0o or 0O is an octal number in Python.

请看下面的语句,它将八进制字面量赋值给变量 −

Look at the below statement assigning octal literal to the variable −

x = 0O34

3. Hexadecimal Literal

类似地,一系列十六进制符号(0 到 9 以及 a 到 f),前缀为 0x 或者 0X,表示 Python 中的十六进制形式的整数。

Similarly, a series of hexadecimal symbols (0 to 9 and a to f), prefixed by 0x or 0X represents an integer in Hexedecimal form in Python.

请看下面的语句,它将十六进制字面量赋值给变量 −

Look at the below statement assigning hexadecimal literal to the variable −

x = 0X1C

但是,需要注意的是,即使你使用八进制或十六进制字面量表示法,Python 在内部仍会将它们作为 int 类型处理。

However, it may be noted that, even if you use octal or hexadecimal literal notation, Python internally treats them as of int type.

Example

# Using Octal notation
x = 0O34
print ("0O34 in octal is", x, type(x))
# Using Hexadecimal notation
x = 0X1c
print ("0X1c in Hexadecimal is", x, type(x))

当您运行此代码时,它将生成以下 output

When you run this code, it will produce the following output

0O34 in octal is 28 <class 'int'>
0X1c in Hexadecimal is 28 <class 'int'>

Python Float Literal

浮点数由整数部分和小数部分组成。按照惯例,小数点符号(.)在浮点数的字面量表示中分隔这两个部分。例如,

A floating point number consists of an integral part and a fractional part. Conventionally, a decimal point symbol (.) separates these two parts in a literal representation of a float. For example,

Example of Float Literal

x = 25.55
y = 0.05
z = -12.2345

对于一位数在小数点前或后的浮点数,如果位数过多,会使用科学计数法进行紧凑的字面量表示。在整数部分之后加上正整数或负整数的符号 E 或 e。

For a floating point number which is too large or too small, where number of digits before or after decimal point is more, a scientific notation is used for a compact literal representation. The symbol E or e followed by positive or negative integer, follows after the integer part.

Example of Float Scientific Notation Literal

例如,数字 1.23E05 等于 123000.00。同样,1.23e-2 等于 0.0123

For example, a number 1.23E05 is equivalent to 123000.00. Similarly, 1.23e-2 is equivalent to 0.0123

# Using normal floating point notation
x = 1.23
print ("1.23 in normal float literal is", x, type(x))
# Using Scientific notation
x = 1.23E5
print ("1.23E5 in scientific notation is", x, type(x))
x = 1.23E-2
print ("1.23E-2 in scientific notation is", x, type(x))

在这里,你会得到以下 output

Here, you will get the following output

1.23 in normal float literal is 1.23 <class 'float'>
1.23E5 in scientific notation is 123000.0 <class 'float''>
1.23E-2 in scientific notation is 0.0123 <class 'float''>

Python Complex Literal

复数包含实数和虚数部分。虚数部分是任何数字(整数或浮点数)乘以“-1”的平方根

A complex number comprises of a real and imaginary component. The imaginary component is any number (integer or floating point) multiplied by square root of "-1"

(√ −1)。在字面量表示中,($\sqrt{−1}$) 表示为“j”或“J”。因此,复数的字面量表示采用形式 x+yj。

(√ −1). In literal representation ($\sqrt{−1}$) is representation by "j" or "J". Hence, a literal representation of a complex number takes a form x+yj.

Example of Complex Type Literal

#Using literal notation of complex number
x = 2+3j
print ("2+3j complex literal is", x, type(x))
y = 2.5+4.6j
print ("2.5+4.6j complex literal is", x, type(x))

该代码将会生成以下 output

This code will produce the following output

2+3j complex literal is (2+3j) <class 'complex'>
2.5+4.6j complex literal is (2+3j) <class 'complex'>

Python String Literal

一个 string 对象是序列 data types in Python 之一。它是一个 Unicode 代码点的不可变序列。代码点是根据 Unicode 标准对应于字符的数字。字符串是 Python 的内置类“str”的对象。

A string object is one of the sequence data types in Python. It is an immutable sequence of Unicode code points. Code point is a number corresponding to a character according to Unicode standard. Strings are objects of Python’s built-in class 'str'.

字符串字面量通过将字符序列括在单引号('hello')、双引号("hello")或三引号('''hello''' 或 """hello""")中写成。

String literals are written by enclosing a sequence of characters in single quotes ('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""").

Example of String Literal

var1='hello'
print ("'hello' in single quotes is:", var1, type(var1))
var2="hello"
print ('"hello" in double quotes is:', var1, type(var1))
var3='''hello'''
print ("''''hello'''' in triple quotes is:", var1, type(var1))
var4="""hello"""
print ('"""hello""" in triple quotes is:', var1, type(var1))

在这里,你会得到以下 output

Here, you will get the following output

'hello' in single quotes is: hello <class 'str'>
"hello" in double quotes is: hello <class 'str'>
''''hello'''' in triple quotes is: hello <class 'str'>
"""hello""" in triple quotes is: hello <class 'str'>

Example of String Literal With Double Quoted Inside String

如果需要将双引号作为字符串的一部分嵌入,则应将字符串本身放到单引号中。另一方面,如果要嵌入单引号文本,则应使用双引号编写字符串。

If it is required to embed double quotes as a part of string, the string itself should be put in single quotes. On the other hand, if single quoted text is to be embedded, string should be written in double quotes.

var1='Welcome to "Python Tutorial" from TutorialsPoint'
print (var1)
var2="Welcome to 'Python Tutorial' from TutorialsPoint"
print (var2)

它将生成以下 output

It will produce the following output

Welcome to "Python Tutorial" from TutorialsPoint
Welcome to 'Python Tutorial' from TutorialsPoint

Python List Literal

List 对象是一种其他数据类型对象的集合。列表是有序的对象的集合,它们不必是同一种类型。可以通过从 0 开始的索引访问集合中的各个对象。

List object in Python is a collection of objects of other data type. List is an ordered collection of items not necessarily of same type. Individual object in the collection is accessed by index starting with zero.

列表对象的文本表示形式通过一个或多个逗号分隔、并用方括号 [] 括起来的对象来表示。

Literal representation of a list object is done with one or more items which are separated by comma and enclosed in square brackets [].

Example of List Type Literal

L1=[1,"Ravi",75.50, True]
print (L1, type(L1))

它将生成以下 output

It will produce the following output

[1, 'Ravi', 75.5, True] <class 'list'>

Python Tuple Literal

Tuple 对象是一种其他数据类型对象的集合。元组是有序的对象的集合,它们不必是同一种类型。可以通过从 0 开始的索引访问集合中的各个对象。

Tuple object in Python is a collection of objects of other data type. Tuple is an ordered collection of items not necessarily of same type. Individual object in the collection is accessed by index starting with zero.

元组对象的文本表示形式通过一个或多个逗号分隔、并用括号 () 括起来的对象来表示。

Literal representation of a tuple object is done with one or more items which are separated by comma and enclosed in parentheses ().

Example of Tuple Type Literal

T1=(1,"Ravi",75.50, True)
print (T1, type(T1))

它将生成以下 output

It will produce the following output

[1, 'Ravi', 75.5, True] <class tuple>

Example of Tuple Type Literal Without Parenthesis

Python 序列的默认分隔符是括号,这意味着一个没有括号的逗号分隔序列也相当于一个元组的声明。

Default delimiter for Python sequence is parentheses, which means a comma separated sequence without parentheses also amounts to declaration of a tuple.

T1=1,"Ravi",75.50, True
print (T1, type(T1))

在这里,您也将获得相同的 output

Here too, you will get the same output

[1, 'Ravi', 75.5, True] <class tuple>

Python Dictionary Literal

像列表或元组一样, dictionary 也是一个集合数据类型。但是,它不是一个序列。它是一个无序的项集合,每个项都是一个键值对。值通过冒号 “:” 符号绑定到键。一个或多个用逗号分隔的键值对放在大括号中,以形成一个字典对象。

Like list or tuple, dictionary is also a collection data type. However, it is not a sequence. It is an unordered collection of items, each of which is a key-value pair. Value is bound to key by the ":" symbol. One or more key:value pairs separated by comma are put inside curly brackets to form a dictionary object.

Example of Dictionary Type Literal

capitals={"USA":"New York", "France":"Paris", "Japan":"Tokyo",
"India":"New Delhi"}
numbers={1:"one", 2:"Two", 3:"three",4:"four"}
points={"p1":(10,10), "p2":(20,20)}

print (capitals, type(capitals))
print (numbers, type(numbers))
print (points, type(points))

键应为一个不可变对象。数字、字符串或元组可以用作键。键在同一个集合中不可出现多次。如果某个键出现多次,则只有最后一个会被保留。值可以是任何数据类型。一个值可以分配给多个键。例如:

Key should be an immutable object. Number, string or tuple can be used as key. Key cannot appear more than once in one collection. If a key appears more than once, only the last one will be retained. Values can be of any data type. One value can be assigned to more than one keys. For example,

staff={"Krishna":"Officer", "Rajesh":"Manager", "Ragini":"officer", "Anil":"Clerk", "Kavita":"Manager"}