数据类型
字符串(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()
------------------------------------------------