版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huitailang1991/article/details/78551956
在项目中遇到了使用uuid作为主键的情况,有时为了测试方便会加几个print在代码里面,后来在一段代码中前后print内容一致的情况下,if 判定不等的条件一直为True,后来想到了之前也遇到了uuid转换为str使用的情况,这是解决问题的一个办法。
这里要说的是print函数打印的问题,如果遇到特殊类型最好带上类型,下面是python官方文档对print的解释:
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.
**All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.** Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.
下面做了一个实验是用print和sys.stdout.write打印的对比:
In [34]: for i in a:
...: sys.stdout.write(i)
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-a7af1453478a> in <module>()
1 for i in a:
----> 2 sys.stdout.write(i)
3
TypeError: write() argument must be str, not UUID
标准输出是不接受UUID的。
In [28]: a = [uuid.uuid4() for n in range(1, 5)]
In [29]: a
Out[29]:
[UUID('6015667f-7f50-4b85-baee-694aa1f93ee6'),
UUID('5d5da498-2f55-46e3-bd0f-73ae574fc686'),
UUID('651f06f3-4680-4d1d-a7ce-223799bfa12b'),
UUID('1ccc9386-97f1-4a2a-ac1d-5bd112b498f1')]
In [30]: print(a)
[UUID('6015667f-7f50-4b85-baee-694aa1f93ee6'), UUID('5d5da498-2f55-46e3-bd0f-73ae574fc686'), UUID('651f06f3-4680-4d1d-a7ce-223799bfa12b'), UUID('1ccc9386-97f1-4a2a-ac1d-5bd112b498f1')]
In [31]: for i in a:
...: print(i)
...:
6015667f-7f50-4b85-baee-694aa1f93ee6
5d5da498-2f55-46e3-bd0f-73ae574fc686
651f06f3-4680-4d1d-a7ce-223799bfa12b
1ccc9386-97f1-4a2a-ac1d-5bd112b498f1
单独打印一个UUID的列表是会带上标记的,但是如果单独打印其中一个的话就会出现print解释中的str转换再打印的情况。