笔记-Python中逗号的作用

时间:2022-11-20 04:26:01

1、用,去掉额外的换行符

笔记-Python中逗号的作用

>>> for i in range(0,5):
...     print i
...
0
1
2
3
4
>>> for i in range(0,5):
...     print i,
...
0 1 2 3 4

很明显 print语句默认的会在后面加上 换行  加了逗号之后 换行 就变成了 空格

赋值表达式的后面加了逗号后,会自动得到一个tuple的对象

>>> a = 1
>>> b = 2,
>>> print type(a)
<type 'int'>
>>> print type(b)
<type 'tuple'>
>>> c = []
>>> d = [],
>>> print type(c)
<type 'list'>
>>> print type(d)
<type 'tuple'>

2.逗号在类型转化中的使用 主要是元组的转换
赋值表达式的后面加了逗号后,会自动得到一个tuple的对象,在作一些与类型相关的工作或需要序列化时,是不能得到期望的结果的。工作中碰到类似灵异现象时,可以把这个放到自己的checklist中了。

>>> print c
[]
>>> print d
([],)
>>> print a
1
>>> print b
(2,)

3、用在 django 列表后面添加,