其它语句

  再谈print()print()函数可自定义分隔符。

>>> print('I', 'like', 'python', sep='_')
I_like_python
>>> print('I', 'like', 'python', sep='**')
I**like**python

  print()函数可自定义结束字符串,以替换默认的换行符。

>>> print('I', 'like', 'python', end=' ')    # 以空格结束
I like python >>>
>>> print('I', 'like', 'python', end='!!!')    # 以!结束
I like python!!!>>>

  赋值魔法:

                  序列解包:以下的赋值方式称为序列解包操作。

>>> x = 3
>>> y = 99
>>> x, y = y, x    # 解包
>>> x
99
>>> y
3
>>> x, y, z = (22, 55, 88)   # 解包
>>> x
22
>>> y
55
>>> z
88

    收集值:可使用星号运算符(*)来收集多余的值。

>>> a, b, *rest = 1, 3, 6, 9, 89, 'python'
>>> a
1
>>> b
3
>>> rest    # 带星号的变量始终返回一个列表
[6, 9, 89, 'python']
>>> lang = 'c c++ python java go c# php'
>>> first, *middle, last = lang.split()
>>> first
'c'
>>> middle    # 带星号的变量始终返回一个列表
['c++', 'python', 'java', 'go', 'c#']
>>> last
'php'

  链式比较:和python支持链式赋值一样,python也支持链式比较。

>>> age = 24
>>> 12 < age < 99
True

   使用del删除:

>>> x = [1, 3, 5]
>>> del x    # 将变量x删除
>>> x    # 变量x不存在了
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = [1, 'w', 9]
>>> y = x
>>> y    # x、y变量同时指向同一个列表对象
[1, 'w', 9]
>>> del x    # 将变量x删除,此时并不会删除对象
>>> x    # 变量x不存在了
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> y    # 变量y依然存在
[1, 'w', 9]

猜你喜欢

转载自www.cnblogs.com/wgbo/p/9584825.html
今日推荐