在 PostgreSQL 中将整数转换为字符串

本教程讨论如何在 PostgreSQL 中将整数转换为字符串。

在 PostgreSQL 中将整数转换为字符串

考虑一个 quiz_score 表,它记录了问答游戏中每个参与者的分数。分数作为字符串而不是整数存储在此表中。

id player_id score
1 1 54
2 2 72
3 3 52
4 4 55
5 5 93
6 6 72
7 7 55
8 8 64
9 9 87
10 10 81

下面是表的 CREATE 语句:

CREATETABLEquiz_score(idintegerNOTNULLGENERATEDALWAYSASIDENTITY,player_idintegerNOTNULL,scoretextNOTNULL,CONSTRAINTquiz_score_pkeyPRIMARYKEY(id));

这是用数据填充表的 INSERT 语句:

INSERTINTOquiz_score(player_id,score)VALUES(1,54),(2,72),(3,52),(4,55),(5,93),(6,72),(7,55),(8,64),(9,87),(10,81);

如果我们被要求找到一个或多个有特定分数的球员,而我们得到的这个分数是整数类型而不是存储在表中的字符串类型,这样的查询:

SELECT*FROMquiz_scoreWHEREscore=72;

会给出以下错误:

ERROR:  operator does not exist: text = integer
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.

按照给出的提示,我们必须将给定的分数(整数类型)转换为字符串,如下所示:

SELECT*FROMquiz_scoreWHEREscore=72::text;

没有抛出错误,结果如下:

id player_id score
2 2 72
6 6 72

将整数转换为字符串的另一种方法如下:

SELECT*FROMquiz_scoreWHEREscore=cast(72astext);

本教程讨论了将整数转换为字符串的两种方法。

在 Python 中将整数转换为枚举

在 Python 中使用括号将整数转换为枚举,例如 print(Sizes(1))。 我们可以将枚举成员的整数值作为参数传递给类,它将返回枚举成员。

from enum import Enum


class Sizes(Enum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3


print(Sizes(1))  # ?️ Sizes.SMALL
print(Sizes(2))  # ?️ Sizes.MEDIUM
print(Sizes(3))  # ?️ Sizes.LARGE

print(Sizes(1).name)  # ?️ SMALL
print(Sizes(1).value)  # ?️ 1

在 Python 中将整数转换为枚举

Sizes(1) 语法允许我们将整数传递给类并获取相应的枚举成员。

当我们提前不知道枚举成员的名称时,这很有用(因为它是从文件中读取或从 API 中获取的)。

如果必须将枚举的成员与整数进行比较,也可以从 IntEnum 类扩展。

from enum import IntEnum


class Sizes(IntEnum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3


print(Sizes(1))  # ?️ Sizes.SMALL
print(Sizes(2))  # ?️ Sizes.MEDIUM
print(Sizes(3))  # ?️ Sizes.LARGE

print(Sizes(1).name)  # ?️ SMALL
print(Sizes(1).value)  # ?️ 1

print(Sizes.SMALL == 1)  # ?️ True
print(Sizes.MEDIUM == 2)  # ?️ True

我们还可以使用方括号以编程方式访问枚举成员。

from enum import Enum


class Sizes(Enum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3


name = 'MEDIUM'

print(Sizes[name].value)  # ?️ 2

print(Sizes['SMALL'].value)  # ?️ 1

这是一个接受用户输入并使用它来访问枚举成员的示例。

from enum import Enum


class Sizes(Enum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3


value = input('Pick size - 1, 2 or 3: ')

print(value)  # ?️ 2

print(Sizes(int(value)))  # ?️ Sizes.MEDIUM

print(Sizes(int(value)).name)  # ?️ MEDIUM
print(Sizes(int(value)).value)  # ?️ 2

如果需要遍历枚举,可以使用简单的 for 循环。

from enum import Enum


class Sizes(Enum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3


for size in Sizes:
    print(size)
    print(size.name, size.value)

我们可以使用列表推导来检查特定值是否在枚举中。

from enum import Enum


class Sizes(Enum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3


# ?️ check enum member type
print(type(Sizes.MEDIUM))  # ?️ <enum 'Sizes'>

# ?️ check if member belongs to Enum
print(isinstance(Sizes.MEDIUM, Sizes))  # ?️ True

values = [member.value for member in Sizes]
print(values)  # ?️ [1, 2, 3]

if 2 in values:
    # ?️ this runs
    print('2 is in values')

列表推导用于对每个元素执行一些操作,或者选择满足条件的元素子集。