# 基本数据类型

## 布尔类型

```>>> 2>1
True
>>> "hello" == "Hello"
False
>>> True and False
False
>>> True or False
True```

## 数值类型

```>>> a = 1234567890
>>> type(a)
<type 'int'>
>>> a = a*10
>>> type(a)
<type 'long'>
>>> 2+2
4
>>> (50-5*6)/4
5
>>> 7/3
2
>>> 7/-3
-3```

Python完全支持float浮点数，不同类型的操作数混在一起时，操作符会把整型转化为浮点数。

```>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5```

Python 也同样支持complex复数，虚部由一个后缀"j"或者"J"来表示。带有非零实部的复数记为"(real+imagj)"，或者也可以通过"complex(real, img)"函数创建。

```>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)```

```>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5```

```>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a)  # sqrt(a.real**2 + a.imag**2)
5.0```

```>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>```

## 字符串类型

```>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'```

```   1 hello = "This is a rather long string containing\n\
2 several lines of text just as you would do in C.\n\
3     Note that whitespace at the beginning of the line is\
4  significant."
5
6 print hello
```

```This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.```

```hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."

print hello```

```This is a rather long string containing\n\
several lines of text much as you would do in C.```

```print """
Usage: thingy [OPTIONS]
-h                        Display this usage message
-H hostname               Hostname to connect to
"""```

```>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'```

```>>> 'str' 'ing'                   #  <-  This is ok
'string'
>>> 'str'.strip() + 'ing'   #  <-  This is ok
'string'
>>> 'str'.strip() 'ing'     #  <-  This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax```

```>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'```

```>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'```

```>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment```

```>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'```

```>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'```

```>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''```

```>>> word[-1]     # The last character
'A'
>>> word[-2]     # The last-but-one character
'p'
>>> word[-2:]    # The last two characters
'pA'
>>> word[:-2]    # Everything except the last two characters
'Hel'```

```>>> word[-0]     # (since -0 equals 0)
'H'```

```>>> word[-100:]
'HelpA'
>>> word[-10]    # error
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range```

``` +---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0   1   2   3   4   5
-5  -4  -3  -2  -1```

```>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34```

```>>> name = 'Swaroop' # This is a string object
>>> name.startswith('Swa')
True
>>> 'a' in name
True
>>> name.find('war')
1
>>> delimiter = '_*_'
>>> mylist = ['Brazil', 'Russia', 'India', 'China']
>>> print delimiter.join(mylist)
Brazil_*_Russia_*_India_*_China```

## unicode字符串

Unicode 针对现代和旧式的文本中所有的字符提供了一个序列。以前，字符只能使用256个序号，文本通常通过绑定代码页来与字符映射。这很容易导致混乱，特别是软件的国际化（ internationalization －－通常写做“i18n”－－“i”+ "i" +“n”）。 Unicode 通过为所有字符定义一个统一的代码页解决了这个问题。

Python 中定义一个 Unicode 字符串和定义一个普通字符串一样简单：

```>>> u'Hello World !'
u'Hello World !'```

```>>> u"你好".encode('utf-8')
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> unicode('你好', 'utf-8')
u'\u4f60\u597d'```

```给C/C++程序员的注释

# 数据结构

## 列表Lists

```   1 #!/usr/bin/python
2
3 # This is my shopping list
4 shoplist = ['apple', 'mango', 'carrot', 'banana']
5
6 print 'I have', len(shoplist),'items to purchase.'
7
8 print '\nI also have to buy rice.'
9 shoplist.append('rice')
10 print 'My shopping list is now', shoplist
11
12 print 'I will sort my list now'
13 shoplist.sort()
14 print 'Sorted shopping list is', shoplist
15
16 print 'The first item I will buy is', shoplist[0]
17 olditem = shoplist[0]
18 del shoplist[0]
19 print 'I bought the', olditem
20 print 'My shopping list is now', shoplist
```

```I have 4 items to purchase.
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice'] ```

• append(x): 把一个元素添加到链表的结尾，相当于 a[len(a):] = [x]
• extend(L): 通过添加指定链表的所有元素来扩充链表，相当于 a[len(a):] = L。
• insert(i, x): 在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引，例如a.insert(0, x) 会插入到整个链表之前，而a.insert(len(a), x) 相当于 a.append(x)。
• remove(x): 删除链表中值为x的第一个元素。如果没有这样的元素，就会返回一个错误。
• pop([i]): 从链表的指定位置删除元素，并将其返回。如果没有指定索引，a.pop()返回最后一个元素。元素随即从链表中被删除。（方法中i两边的方括号表示这个参数是可选的，而不是要求你输入一对方括号，你会经常在Python 库参考手册中遇到这样的标记。）
• index(x): 返回链表中第一个值为x的元素的索引。如果没有匹配的元素就会返回一个错误。
• count(x): 返回x在链表中出现的次数。
• sort(): 对链表中的元素进行适当的排序。
• reverse(): 倒排链表中的元素。

```>>> a = [66.6, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.6), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.6, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.6, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.6]
>>> a.sort()
>>> a
[-1, 1, 66.6, 333, 333, 1234.5]```

```>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]```

```>>> queue = ["Eric", "John", "Michael"]
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']```

## 元组Tuples

```   1 #!/usr/bin/python
2
3 zoo = ('wolf', 'elephant', 'penguin')
4 print 'Number of animals in the zoo is', len(zoo)
5
6 new_zoo = ('monkey', 'dolphin', zoo)
7 print 'Number of animals in the new zoo is', len(new_zoo)
8 print 'All animals in new zoo are', new_zoo
9 print 'Animals brought from old zoo are', new_zoo[2]
10 print 'Last animal brought from old zoo is', new_zoo[2][2]
```

```Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin ```

## 字符串替换

```age = 22
name = 'Swaroop'

print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name ```

```Swaroop is 22 years old
Why is Swaroop playing with that python? ```

print语句可以使用跟着%符号的项目元组的字符串。这些字符串具备定制的功能。定制让输出满足某种特定的格式。定制可以是%s表示字符串或%d表示整数。元组必须按照相同的顺序来对应这些定制。

Python在这里所做的是把元组中的每个项目转换成字符串并且用字符串的值替换定制的位置。因此%s被替换为变量name的值，依此类推。

print的这个用法使得编写输出变得极其简单，它避免了许多字符串操作。它也避免了我们一直以来使用的逗号。

## 字典Dictionaries

```   1 #!/usr/bin/python
2
3 # 'ab' is short for 'a'ddress'b'ook
4
5 ab = {       'Swaroop'   : '[email protected]',
6              'Larry'     : '[email protected]',
7              'Matsumoto' : '[email protected]',
8              'Spammer'   : '[email protected]'
9      }
10
11 print "Swaroop's address is %s" % ab['Swaroop']
12
13 # Adding a key/value pair
14 ab['Guido'] = '[email protected]'
15
16 # Deleting a key/value pair
17 del ab['Spammer']
18
19 print '\nThere are %d contacts in the address-book\n' % len(ab)
20
21 print "\nGuido's address is %s" % ab['Guido']
22
23 print "\nAll contacts: "
24 print a.keys()
25
27 print ab.values()
```

```Swaroop's address is [email protected]

There are 4 contacts in the address-book

All contacts:
['Swaroop', 'Matsumoto', 'Larry', 'Guido']

['[email protected]', '[email protected]', '[email protected]', '[email protected]']```

## 序列

```   1 #!/usr/bin/python
2
3 shoplist = ['apple', 'mango', 'carrot', 'banana']
4
5 # Indexing or 'Subscription' operation
6 print 'Item 0 is', shoplist[0]
7 print 'Item 1 is', shoplist[1]
8 print 'Item 2 is', shoplist[2]
9 print 'Item 3 is', shoplist[3]
10 print 'Item -1 is', shoplist[-1]
11 print 'Item -2 is', shoplist[-2]
12
13 # Slicing on a list
14 print 'Item 1 to 3 is', shoplist[1:3]
15 print 'Item 2 to end is', shoplist[2:]
16 print 'Item 1 to -1 is', shoplist[1:-1]
17 print 'Item start to end is', shoplist[:]
18
19 # Slicing on a string
20 name = 'swaroop'
21 print 'characters 1 to 3 is', name[1:3]
22 print 'characters 2 to end is', name[2:]
23 print 'characters 1 to -1 is', name[1:-1]
24 print 'characters start to end is', name[:]
```

```Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop ```

```>>> 2 in [1,2,3]
True
>>> 'A' in ('a', 'b', 'c')
False
>>> 'H' in 'Hello world'
True```

## 引用

```   1 #!/usr/bin/python
2
3 print 'Simple Assignment'
4 shoplist = ['apple', 'mango', 'carrot', 'banana']
5 mylist = shoplist # mylist is just another name pointing to the same object!
6
7 del shoplist[0]
8
9 print 'shoplist is', shoplist
10 print 'mylist is', mylist
11 # notice that both shoplist and mylist both print the same list without
12 # the 'apple' confirming that they point to the same object
13
14 print 'Copy by making a full slice'
15 mylist = shoplist[:] # make a copy by doing a full slice
16 del mylist[0] # remove first item
17
18 print 'shoplist is', shoplist
19 print 'mylist is', mylist
20 # notice that now the two lists are different
```

```Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana'] ```

## 列表推导式 List Comprehensions

```   1 #!/usr/bin/python
2
3 listone = [2, 3, 4]
4 listtwo = [2*i for i in listone if i > 2]
5 print listtwo
```

`[6, 8]`

## 类型转换

```>>> a = False
>>> str(a)
'False'
>>> int(a)
0
>>> b = 10.5
>>> int(b)
10
>>> c = [1,2,3,4,5]
>>> tuple(c)
(1, 2, 3, 4, 5)
>>> d = '123.45'
>>> float(d)
123.45
>>> int(d)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 123.45```

## 文件Files

```   1 #!/usr/bin/python
2
3 poem = '''\
4 Programming is fun
5 When the work is done
6 if you wanna make your work also fun:
7         use Python!
8 '''
9
10 f = file('poem.txt', 'w') # open for 'w'riting
11 f.write(poem) # write text to file
12 f.close() # close the file
13
14 f = file('poem.txt')
15 # if no mode is specified, 'r'ead mode is assumed by default
16 while True:
18     if len(line) == 0: # Zero length indicates EOF
19         break
20     print line,
21     # Notice comma to avoid automatic newline added by Python
22 f.close() # close the file
```

```\$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python! ```

```Programming is fun
When the work is done
if you wanna make your work also fun:
use Python! ```

# 运算符

## 运算符表

 运算符 名称 说明 例子 + 加 两个对象相加 3 + 5得到8。'a' + 'b'得到'ab'。 - 减 得到负数或是一个数减去另一个数 -5.2得到一个负数。50 - 24得到26。 * 乘 两个数相乘或是返回一个被重复若干次的字符串 2 * 3得到6。'la' * 3得到'lalala'。 ** 幂 返回x的y次幂 3 ** 4得到81（即3 * 3 * 3 * 3） / 除 x除以y 4/3得到1（整数的除法得到整数结果）。4.0/3或4/3.0得到1.3333333333333333 // 取整除 返回商的整数部分 4 // 3.0得到1.0 % 取模 返回除法的余数 8%3得到2。-25.5%2.25得到1.5 << 左移 把一个数的比特向左移一定数目（每个数在内存中都表示为比特或二进制数字，即0和1） 2 << 2得到8。——2按比特表示为10 >> 右移 把一个数的比特向右移一定数目 11 >> 1得到5。——11按比特表示为1011，向右移动1比特后得到101，即十进制的5。 & 按位与 数的按位与 5 & 3得到1。 | 按位或 数的按位或 5 | 3得到7。 ^ 按位异或 数的按位异或 5 ^ 3得到6 ~ 按位翻转 x的按位翻转是-(x+1) ~5得到-6。 < 小于 返回x是否小于y。所有比较运算符返回True表示真，返回False表示假。 5 < 3返回0（即False）而3 < 5返回1（即True）。比较可以被任意连接：3 < 5 < 7返回True。 > 大于 返回x是否大于y 5 > 3返回True。如果两个操作数都是数字，它们首先被转换为一个共同的类型。否则，它总是返回False。 <= 小于等于 返回x是否小于等于y x = 3; y = 6; x <= y返回True。 >= 大于等于 返回x是否大于等于y x = 4; y = 3; x >= y返回True。 == 等于 比较对象是否相等 x = 2; y = 2; x == y返回True。x = 'str'; y = 'stR'; x == y返回False。x = 'str'; y = 'str'; x == y返回True。 != 不等于 比较两个对象是否不相等 x = 2; y = 3; x != y返回True。 not 布尔“非” 如果x为True，返回False。如果x为False，它返回True。 x = True; not y返回False。 and 布尔“与” 如果x为False，x and y返回False，否则它返回y的计算值。 x = False; y = True; x and y，由于x是False，返回False。在这里，Python不会计算y，因为它知道这个表达式的值肯定是False（因为x是False）。这个现象称为短路计算。 or 布尔“或” 如果x是True，它返回True，否则它返回y的计算值。 x = True; y = False; x or y返回True。短路计算在这里也适用。

## 运算符优先级

 运算符 描述 lambda Lambda表达式 or 布尔“或” and 布尔“与” not x 布尔“非” in，not in 成员测试 is，is not 同一性测试 <，<=，>，>=，!=，== 比较 | 按位或 ^ 按位异或 & 按位与 <<，>> 移位 +，- 加法与减法 *，/，% 乘法、除法与取余 +x，-x 正负号 ~x 按位翻转 ** 指数 x.attribute 属性参考 x[index] 下标 x[index:index] 寻址段 f(arguments...) 函数调用 (experession,...) 绑定或元组显示 [expression,...] 列表显示 {key:datum,...} 字典显示 expression,... 字符串转换

# end

Python语言的数据类型 (last edited 2009-12-07 20:27:23 by czk)

ch3n2k.com | Copyright (c) 2008 czk. 浙ICP备06000584号