本文部分参考了“小甲鱼的python教程”、《python基础教程(第二版)》,在此表示感谢。侵删。
1.输入&输出
输出:
print"hello world"
hello world
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print"Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
7
Is it true that 3 + 2 < 5 - 7?
False
输入:
name = raw_input("Please input your name:")
print "your name is %r" %name
除非对input有特殊的需要,否则一般使用rew_input函数。
2.字符串
"hello world!"
'hello world!'
print "hello world!"
hello world!
拼接字符串:
print "hello," + "python"
hello, python
注意:repr和str各自的用法。
repr(object):返回值的字符串表示形式
str(object):将值转换为字符串
- split:用来将字符串分割成序列。
>>> '2+1+0'.split('+')
['2', '1', '0']
3.list & tuple
- list
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
分片赋值:
>>> numbers = [5, 3, 3]
>>> numbers[1:] = [2, 0]
>>> numbers
[5, 2, 0]
利用分片赋值删除元素:
>>> numbers
[5, 2, 0]
>>> numbers[1:3] = []
>>> numbers
[5]
注意:append, count, extend, index, insert, pop, remove, reserve, sort各自的用法。
- tuple
与列表类似。tuple能满足特定的需求,而list更能满足对序列的所有需求。
4.dictionary
主要说一下dictionary的格式化字符串。
这里引用《python基础教程(第二版)》中的例子说明其用法(html)
>>> template = '''<html>
<head><title>%(title)s</title></head>
<body>
<h1>%(title)s</hl>
<p>%(text)s</p>
</body>'''
>>> data = {'title': 'my home page', 'text': 'welcome to my home page!'}
>>> print template % data
<html>
<head><title>my home page</title></head>
<body>
<h1>my home page</hl>
<p>welcome to my home page!</p>
</body>
字典方法:注意clear, copy, fromkeys, get, pop的用法。