Skip to content

基本数据类型

  • number(数字)
  • str(字符串)
  • bool(布尔类型)
  • list(列表): 类似 js 中的数组
  • tuple(元组)
  • set(集合)
  • dict(字典): 类似 js 中的对象(k=v)
python
age = 10       # int
name = "tom"   # str
is_boy = true  # bool
friends = [    # list
    "jerry",
    "alex",
]
info = {       # dict
    "firstname": "john",
    "lastname": "doe",
    "age": 28,
}

获取变量类型

type 方法返回的是变量类型字符串

python
age = 10      # int
name = "tom"  # str
is_boy = true # bool
friends = [   # list
    "jerry",
    "alex",
]
info = {      # dict
    "firstName": "John",
    "lastName": "Doe",
    "age": 28,
}

print(type(age))
print(type(name))
print(type(is_boy))
print(type(info))

获取变量的数据类型

python
variable = "str";
print(type(variable)); # <class 'str'>

判断变量数据类型

isinstance 方法可以判断某个数据是否是某个类型, 返回一个 Boolean 值

python
print(isinstance("hello", str)) # True
print(isinstance(11, str)) # False

数据类型转换

python
print(int(1.2)) # 1
print(int("1")) # 1
# print(int("a1"))            # 报错: 必须是数字字符串
# print(int([1,2]))           # 报错: list 转不了
# print(int(('a', 1, False))) # 报错: tuple 转不了
python
print(float(1))       # 1.0
print(float("3.14"))  # 3.14
print(float(" -2 "))  # -2.0(自动去除首尾空格)
# print(float("abc"))    # 报错: 无法解析非数字字符串
# print(float([1]))      # 报错: list 不能转 float
# print(float(('a', 1))) # 报错: tuple 不能转 float
python
print(str(10))        # int   转 str, 输出: "10"
print(str(10.11))     # float 转 str, 输出: "10.11"
print(str(False))     # False 转 str, 输出: "False"
print(str(True))      # True  转 str, 输出: "True"

v = str([1,2,3])
t = type(v)
print(v, t)           # list 转 str, 输出: "[1, 2, 3]" <class 'str'>

v2 = str(('a', 1, '2'))
t2 = type(v2)
print(v2, t2)         # tuple 转 str, 输出: "('a', 1, '2')" <class 'str'>
python
print(bool(1))        # True
print(bool(0))        # False
print(bool(-1))       # True
print(bool(0.0))      # False
print(bool(""))       # False
print(bool("hello"))  # True
print(bool([]))       # False
print(bool([1]))      # True
print(bool(()))       # False
print(bool((0,)))     # True
print(bool(None))     # False
# 所有 `空` 或 `零` 值为 False,其余为 True
python
print(list("abc"))            # str   转 list, 输出: ['a', 'b', 'c']
print(list((1, 2, 3)))        # tuple 转 list, 输出: [1, 2, 3]
print(list({1, 2, 3}))        # set   转 list, 输出: [1, 2, 3](顺序无法确定)
print(list({'a': 1, 'b': 2})) # dict  转 list, 输出: ['a', 'b']
# print(list(123))            # int 不能转 list, 必须是可迭代的数据才能转 list
# print(list(11.22))          # float 不能转 list
python
print(tuple("abc"))            # str  转 tuple, 输出: ('a', 'b', 'c')
print(tuple([1, 2, 3]))        # list 转 tuple, 输出: (1, 2, 3)
print(tuple({1, 2, 3}))        # set  转 tuple, 输出: (1, 2, 3)(顺序不确定)
print(tuple({'a': 1, 'b': 2})) # dict 转 tuple, 输出: ('a', 'b')(只取键)
# print(tuple(123))            # 报错: int 不可迭代
# print(tuple(1.2))            # 报错: float 不能转

Released under the MIT License.