Python代码备忘录

数据类型

字符串(String)

当字符串被创建时,修改或删除字符串的一部分是不允许的。这是因为字符串是不可变的,因此一旦分配了字符串,就无法更改其元素。 只能将新字符串重新分配给相同的名称。

>>> str_1[-1] = 'c'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del str[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object does not support item deletion

但是,删除整个字符串是允许的。

>>> del str_1
>>> print(str_1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'str_1' is not defined

无视转义字符的两种方法:

>>> str_2 = 'hello \\n world'
>>> print(str_2)
hello \n world

>>> print(r'hello \n world')
hello \n world
列表(List)

添加:

a.append(2)

删除:

a.pop()
a.remove()
字典

最常用:

a.setdefault(1,'one')

#更新字典

In [8]: a
Out[8]: {
   }

In [9]: b = {
   1:'one'}

In [10]: a.update(b)

In [11]: a
Out[11]: {
   1: 'one'}

取“键”,“值”

a.keys() #所有键
a.values() #所有值

#判断

key in a

#获取值

a.get(1)
字符串

判断字符串中是否有某个子串:

>>> 'he' in 'hello'
True
>>> 'se' in 'hello'
False

变量

Global关键字:

当出现以下程序逻辑时会报错:

In [1]: a = 1

In [2]: def f():
   ...:     a = a + 1

In [3]: f()
------------------------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值