number
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
----Python Number 类型转换
int(x [,base ]) 将x转换为一个整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串
字符串
a = "Hello"
b = "Python"
print "a + b 输出结果:", a + b // HelloPython
print "a * 2 输出结果:", a * 2 // HelloHello
print "a[1] 输出结果:", a[1] // e
print "a[1:4] 输出结果:", a[1:4] // ell
print a.endswith('llo'); // true
if( "H" in a) :
print "H 在变量 a 中"
else :
print "H 不在变量 a 中"
class定义
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
列表(list)
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print "list1[0]: ", list1[0] // list1[0]: physics
print "list2[1:5]: ", list2[1:5] // list2[1:5]: [2, 3, 4, 5]
list.append('Google') ## 使用 append() 添加元素
del list1[2]
.len
.max
.min
.list
例: aTuple = (123, 'runoob', 'google', 'abc');
aList = list(aTuple)
.append
.remove
.reverse
.sort
.count
.insert
.pop
---------
>>>L = ['Google', 'Runoob', 'Taobao']
>>> L[2] 读取列表中第三个元素
'Taobao'
>>> L[-2] 读取列表中倒数第二个元素
'Runoob'
>>> L[1:] 从第二个元素开始截取列表
['Runoob', 'Taobao']
元组
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
# 创建一个新的元组
tup3 = tup1 + tup2
del tup1
len((1, 2, 3)) // 3
(1, 2, 3) + (4, 5, 6) // (1, 2, 3, 4, 5, 6)
('Hi!',) * 4 // ('Hi!', 'Hi!', 'Hi!', 'Hi!')
3 in (1, 2, 3) // true
for x in (1, 2, 3): print x // 1 2 3
L = ('spam', 'Spam', 'SPAM!')
L[2] // 读取第三个元素 // 'SPAM!'
L[-2] // 反向读取,读取倒数第二个元素 // 'Spam'
L[1:] 截取元素 // ('Spam', 'SPAM!')
.cmp
.len
.max
.min
.tuple
字典(Dictionary)
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # 更新
dict['School'] = "RUNOOB" # 添加
del dict['Name'] # 删除键是'Name'的条目
dict.clear() # 清空字典所有条目
del dict # 删除字典
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
2)键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行
.cmp
.len
.str
.type
.clear
.copy
.fromkeys
.get
.has_key
.items
.keys
.update
.setdefault
.values
pop
popitem