python 基本类型的创建方法
1、int
class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal字面 in the
| given base. The literal can be preceded在什么之前 by '+' or '-' and be surrounded环绕
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
# 1、没有参数转换为0
print(int())
print('*' * 50) # 2、一个数字转换为整数
print(int(10.6))
print('*' * 50) # 3、将一个字符串转换为整数
print(int('', 16))
print(int('', 10))
print(int('', 8))
print(int('', 2))
print('*' * 50) # 4、将一个字节流或字节数组转换为整数
print(int(b'', 16))
print(int(b'', 10))
print(int(b'', 8))
print(int(b'', 2))
print('*' * 50) # 5、base=0时,按字面值进行转换
print(int('0x111', 0))
print(int('', 0))
print(int('0o111', 0))
print(int('0b111', 0))
print('*' * 50)
0
**************************************************
10
**************************************************
273
111
73
7
**************************************************
273
111
73
7
**************************************************
273
111
73
7
**************************************************
2、bool
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
3、float
class float(object)
| float(x) -> floating point number
|
| Convert a string or number to a floating point number, if possible.
print(float(123))
print(float(''))
123.0
123.0
4、str
class str(object)
| str(object='') -> str
# 对象转字符串
| str(bytes_or_buffer[, encoding[, errors]]) -> str
# 字节流转字符串
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
# 1、对象转字符串
# 如果对象存在__str__方法,就调用它,否则调用__repr__
print(str([1, 2, 3])) # 调用了列表的__str__
print([1, 2, 3].__str__())
print(str(type)) # 调用了列表的__repr__
print(type.__repr__(type))
print('*' * 50)
# 注意
print(str(b'')) # 这个是对象转字符串,不是字节流转字符串
print(b''.__str__())
print('*' * 50) # 2、字节流转字符串
# 第一个参数是字节流对象
# 第二个参数是解码方式,默认是sys.getdefaultencoding()
# 第三个参数是转换出错时的处理方法,默认是strict
import sys
print(sys.getdefaultencoding())
print(str(b'', encoding='utf-8')) # 字节流转字符串的第一种方法
# 字节流转换字符串
print(b''.decode(encoding='utf-8')) # 字节流转字符串的第二种方法
[1, 2, 3]
[1, 2, 3]
<class 'type'>
<class 'type'>
**************************************************
b''
b''
**************************************************
utf-8
123456
123456
5、bytearray
class bytearray(object)
| bytearray(iterable_of_ints) -> bytearray<br>
# 元素必须为[0 ,255] 中的整数
| bytearray(string, encoding[, errors]) -> bytearray<br>
# 按照指定的 encoding 将字符串转换为字节序列
| bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer<br>
# 字节流
| bytearray(int) -> bytes array of size given by the parameter initialized with null bytes<br>
# 返回一个长度为 source 的初始化数组
| bytearray() -> empty bytes array<br>
# 默认就是初始化数组为0个元素
|
| Construct a mutable bytearray object from:
| - an iterable yielding integers in range(256)
# bytearray([1, 2, 3])
| - a text string encoded using the specified encoding
# bytearray('你妈嗨', encoding='utf-8')
| - a bytes or a buffer object
# bytearray('你妈嗨'.encode('utf-8'))
| - any object implementing the buffer API.
| - an integer
# bytearray(10)
# 1、0个元素的字节数组
print(bytearray())
print('*' * 50) # 2、指定个数的字节数组
print(bytearray(10))
print('*' * 50) # 3、int类型的可迭代对象,值在0-255
print(bytearray([1, 2, 3, 4, 5]))
print('*' * 50) # 4、字符串转字节数组
print(bytearray('', encoding='utf-8'))
print('*' * 50) # 5、字节流转字符串
print(bytearray(b''))
print('*' * 50)
bytearray(b'')
**************************************************
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
**************************************************
bytearray(b'\x01\x02\x03\x04\x05')
**************************************************
bytearray(b'')
**************************************************
bytearray(b'')
**************************************************
6、bytes
class bytes(object)
| bytes(iterable_of_ints) -> bytes<br> # bytes([1, 2, 3, 4]) bytes must be in range(0, 256)
| bytes(string, encoding[, errors]) -> bytes<br> # bytes('你妈嗨', encoding='utf-8')
| bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer<br> #
| bytes(int) -> bytes object of size given by the parameter initialized with null bytes
| bytes() -> empty bytes object
|
| Construct an immutable array of bytes from:
| - an iterable yielding integers in range(256)
| - a text string encoded using the specified encoding
| - any object implementing the buffer API.
| - an integer
# 1、一个空字节流
print(bytes())
print('*' * 50) # 2、一个指定长度的字节流
print(bytes(10))
print('*' * 50) # 3、int类型的可迭代对象,值0-255
print(bytes([1, 2, 3, 4, 5]))
print('*' * 50) # 4、string转bytes
print(bytes('', encoding='utf-8'))
print('*' * 50) print(''.encode(encoding='utf-8'))
print('*' * 50) # 5、bytearry转bytes print(bytes(bytearray([1, 2, 3, 4, 5])))
print('*' * 50)
b''
**************************************************
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
**************************************************
b'\x01\x02\x03\x04\x05'
**************************************************
b''
**************************************************
b''
**************************************************
b'\x01\x02\x03\x04\x05'
**************************************************
7、list
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
# 1、返回一个空列表
print(list()) # 2、将一个可迭代对象转换成列表
print(list('string'))
print(list([1, 2, 3, 4]))
print(list({'one': 1, 'two': 2})) # 3、参数是一个列表
l = [1, 2, 3, 4]
print(id(l))
l2 = list(l) # 创建了一个新的列表,与元组不同
print(id(l2))
[]
['s', 't', 'r', 'i', 'n', 'g']
[1, 2, 3, 4]
['one', 'two']
35749640
35749704
字典转列表:
d = {'one': 1, 'two': 2}
for i in d:
print(i)
print('*'*50)
for i in d.keys():
print(i)
print('*'*50)
for i in d.values():
print(i)
print('*'*50)
for i in d.items():
print(i)
print('*'*50)
print(list(d))
print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))
print('*'*50)
print(d)
print(d.keys())
print(d.values())
print(d.items())
print('*'*50)
print(type(d))
print(type(d.keys()))
print(type(d.values()))
print(type(d.items()))
print('*'*50)
one
two
**************************************************
one
two
**************************************************
1
2
**************************************************
('one', 1)
('two', 2)
**************************************************
['one', 'two']
['one', 'two']
[1, 2]
[('one', 1), ('two', 2)]
**************************************************
{'one': 1, 'two': 2}
dict_keys(['one', 'two'])
dict_values([1, 2])
dict_items([('one', 1), ('two', 2)])
**************************************************
<class 'dict'>
<class 'dict_keys'>
<class 'dict_values'>
<class 'dict_items'>
**************************************************
8、tuple
class tuple(object)
| tuple() -> empty tuple
# 创建一个空的元组
| tuple(iterable) -> tuple initialized from iterable's items
# 将一个可迭代对象转成元组
|
| If the argument is a tuple, the return value is the same object.
# 如果参数时一个元组,返回一个相同的对象
# 1、返回一个空元组
print(tuple()) # 2、将一个可迭代对象转换成元组
print(tuple('string'))
print(tuple([, , , ]))
print(tuple({'one': , 'two': })) # 3、参数是一个元组
tp = (, , , )
print(id(tp))
tp2 = tuple(tp)
print(id(tp2))
()
('s', 't', 'r', 'i', 'n', 'g')
(1, 2, 3, 4)
('one', 'two') # 参数是字典的时候,返回的是键值的元组
35774616
35774616
字典转元组:
d = {'one': 1, 'two': 2}
for i in d:
print(i)
print('*'*50)
for i in d.keys():
print(i)
print('*'*50)
for i in d.values():
print(i)
print('*'*50)
for i in d.items():
print(i)
print('*'*50)
print(tuple(d))
print(tuple(d.keys()))
print(tuple(d.values()))
print(tuple(d.items()))
print('*'*50)
print(d)
print(d.keys())
print(d.values())
print(d.items())
print('*'*50)
print(type(d))
print(type(d.keys()))
print(type(d.values()))
print(type(d.items()))
print('*'*50)
one
two
**************************************************
one
two
**************************************************
1
2
**************************************************
('one', 1)
('two', 2)
**************************************************
('one', 'two')
('one', 'two')
(1, 2)
(('one', 1), ('two', 2))
**************************************************
{'one': 1, 'two': 2}
dict_keys(['one', 'two'])
dict_values([1, 2])
dict_items([('one', 1), ('two', 2)])
**************************************************
<class 'dict'>
<class 'dict_keys'>
<class 'dict_values'>
<class 'dict_items'>
**************************************************
9、dict
class dict(object)
| dict() -> new empty dictionary # 空字典
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs<br> # dict([('one', 1), ('two', 2)])
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
# 1、空字典
print(dict())
print('*' * 50) # 2、从一个映射对象创建字典
print(dict([('one', 1), ('two', 2)]))
print('*' * 50) # 3、从一个带key和value的可迭代对象创建字典
d = {'one': 1, 'two': 2}
dt = {}
for k, v in d.items():
dt[k] = v
print(dt)
print('*' * 50) # 4、以name=value对创建字典
print(dict(one=1, two=2))
{}
**************************************************
{'one': 1, 'two': 2}
**************************************************
{'one': 1, 'two': 2}
**************************************************
{'one': 1, 'two': 2}
10、set
class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
# 1、创建空集合
print(set()) # 2、可迭代对象转换为集合
print(set([1, 2, 1, 2]))
set() # 空集合这样表示,{}表示字典
{1, 2}
11、frozenset
class frozenset(object)
| frozenset() -> empty frozenset object
| frozenset(iterable) -> frozenset object
|
| Build an immutable unordered collection of unique elements.
# 与set的区别是不可变得
# 1、创建空集合
print(frozenset()) # 2、可迭代对象转换为集合
fs = frozenset([1, 2, 1, 2])
print(fs) # 3、为set和frozenset对象添加元素
s = set((100, ))
s.add(10)
print(s) fs.add(10)
frozenset()
frozenset({1, 2})
{10, 100}
Traceback (most recent call last):
File "1.py", line 14, in <module>
fs.add(10)
AttributeError: 'frozenset' object has no attribute 'add'
12、complex
class complex(object)
| complex(real[, imag]) -> complex number
|
| Create a complex number from a real part and an optional imaginary part.
| This is equivalent to (real + imag*1j) where imag defaults to 0.
print(complex(10))
print(complex(10, 10))
a = 10 + 0j
print(a)
print(a == 10)
(10+0j)
(10+10j)
(10+0j)
True
13、type
class type(object)
| type(object_or_name, bases, dict)
# 创建一个类
| type(object) -> the object's type
# 查看这个对象的类型
| type(name, bases, dict) -> a new type
#
# type功能1,判断对象的类型
print(type(int))
print(type()) # type功能2,动态创建类
# 第一个参数是字符串
# 第二个参数是父类的元组
# 第三个参数是属性的字典
class Animal():
pass Dog = type('Dog', (Animal,), {})
dog = Dog() print(type(Dog))
print(type(dog))
python 基本类型的创建方法的更多相关文章
- python字符类型的一些方法
python 字符串和字节互转换.bytes(s, encoding = "utf8") str(b, encoding = "utf-8") i.isspac ...
- python pandas ---Series,DataFrame 创建方法,操作运算操作(赋值,sort,get,del,pop,insert,+,-,*,/)
pandas 是基于 Numpy 构建的含有更高级数据结构和工具的数据分析包 pandas 也是围绕着 Series 和 DataFrame 两个核心数据结构展开的, 导入如下: from panda ...
- Python 错误类型及解决方法
SyntaxError: invalid syntax 表示“语法错误:不正确的语法” 检查代码的缩进,代码格式是否正确,Python的缩进一般为四个空格,tab键尽量不要用. In ...
- python序列类型字符串的方法L.index()与L.find()区别
首先官方解释 S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring ...
- gluster 卷的类型及创建方法
基本卷: 分布式卷 文件随机分布在brick中,提升读写性能 不提供数据冗余,最大化利用磁盘空间 # gluster volume create test-volume server1:/exp1 s ...
- python基础===列表类型的所有方法
链表类型有很多方法,这里是链表类型的所有方法: append(x) 把一个元素添加到链表的结尾,相当于a[len(a):] = [x] extend(L) 通过添加指定链表的所有元素来扩充链表,相当于 ...
- Python序列类型各自方法
在Python输入dir(str).dir(list).dir(tuple)可查看各种序列类型的所有方法. 对于某个方法不懂怎么使用的情况,可以直接help(str.split)对某个方法进行查询. ...
- Python:数字类型和字符串类型的内置方法
一.数字类型内置方法 1.1 整型的内置方法 作用 描述年龄.号码.id号 定义方式 x = 10 x = int('10') x = int(10.1) x = int('10.1') # 报错 内 ...
- Python 变量类型
Python 变量类型 变量存储在内存中的值.这就意味着在创建变量时会在内存中开辟一个空间. 基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中. 因此,变量可以指定不同的数据 ...
随机推荐
- JAVA程序设计(12.3)---- 监听器0基础应用:五子棋
1.制作五子棋游戏软件 由于老师已经基本做完了.重做的时候快了非常多--可是还是感觉思维非常混乱-- 哪边先哪边后,哪个方法在哪边好之类的问题 太纠结了-- 先是窗体 内部类:鼠标适配器 窗体的构造 ...
- vmware下安装mac os虚拟机问题,最后还是最终攻克了被一个小失误给陷害了
今天决定来体验一下苹果系统.虚拟机文件大概用了一天半时间才下载完毕,解压后是39G大小,赶紧安装VMWARE.然后载入虚拟机文件体验.開始当我苹果标志出来的时候,我以为成功了.但是那个小齿轮一直在转, ...
- three.js 源代码凝视(十五)Math/Plane.js
商域无疆 (http://blog.csdn.net/omni360/) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:商域无疆 - 本博客专注于 敏捷开发 ...
- 心情日记app总结 数据存储+服务+广播+listview+布局+fragment+intent+imagebutton+tabactivity+美工
---恢复内容开始--- 结果截图如下: 第一张图是程序主界面,主要是显示记事列表的一些个事件.旁边的侧拉框是自己登陆用的.可以设置密码.可以查看反馈与关于等信息. 点击第一张图片下方的图标,会显示不 ...
- Yii框架中安装srbac扩展方法
首先,下载srbac_1.3beta.zip文件和对应的blog-srbac_1.2_r228.zip 问什么要下载第二个文件,后面就知道了. 按照手册进行配置: 解压缩srbac_1.3beta.z ...
- 解决查询access数据库含日文出现“内存溢出”问题
ACCESS有个BUG,那就是在使用 like 搜索时如果遇到日文就会出现“内存溢出”的问题,提示“80040e14/内存溢出”. 会出问题的SQL: where title like '%" ...
- ViewPagerIndicator 取代TabHost,实现滑动tab,引导页等效果
https://github.com/eltld/ViewPagerIndicator 取代TabHost,实现滑动tab,引导页等效果
- notpad++快捷键
Notpad++快捷键 Notepad++选中行操作 快捷键 使用技巧 作者: Rememberautumn 分类: 其他 发布时间: 2014-09-04 14:18 阅读: 60,106 微信小 ...
- VC++中全局变量的问题(转)
全局变量一般这样定义:1.在一类的.cpp中定义 int myInt;然后再在要用到的地方的.cpp里extern int myInt:这样就可以用了. 2.在stdafx.cpp中加入:int my ...
- 把node加入master节点时,日志内容分析
root@node1:~# kubeadm --token bggbum.mj3ogzhnm1wz07mj --discovery-token-ca-cert-hash sha256:8f02f833 ...