python学习笔记:
>>> input("The meaning of life: ")
The meaning of life: 42
42
>>> input("x:")
x:4
4
>>> input("y:")
y:2
2
>>> printx*y
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
printx*y
NameError: name 'printx' is not defined
------------------------------------------------------------
>>> 2**3
8
>>> pow(2,3)
8
>>> import math
>>> math.floor(32.9)
32.0
>>> int(math.floor(32.9))
32
>>> from math import floor
>>> floor(32.9)
32.0
>>> int(floor(32.9))
32
-------------------------------------------------------------
-、input和raw_input的区别:input会假设用户输入的是合法的Python表达式(或多或少与repr函数相反的意思)。如果以字符串输入则程序运行是没有问题的。对此,可以使用raw_input替代input,raw_input则会把所有的输入当作原始数据(raw data),然后将其放入字符串中。
1、
name=input("what's your name?")
print "hello,"+name+"!"
>>>
what's your name?jack
Traceback (most recent call last):
File "C:\Users\hp\Desktop\123.py", line 1, in <module>
name=input("what's your name?")
File "<string>", line 1, in <module>
NameError: name 'jack' is not defined
>>>
2、
print "Hello,world!"
name = raw_input("What is you name?")
print "hello,"+name+"!"
raw_input("Press<enter>")
-------------------------------------------------------------
>>> "\"hello,world!\"she said" # 使用"\"转义字符
'"hello,world!"she said'
>>> "let's say"'"hello,world!"'
'let\'s say"hello,world!"'
>>> "Hello,"+"world!"
'Hello,world!'
>>> x="Hello,"
>>> y="world1"
>>> x+y
'Hello,world1'
--------------------------------------------------------------
>>> print "hello,\ # 行后面+"\"代表转义,后面每行可以输入数据,和上面意思一样。
world!"
hello,world!
>>>
--------------------------------------------------------------
1、字符串表示str、repr(str函数会把值转换为合理形式的字符串,以便用户可以理解;而repr会创建一个字符串,它以合法的Python表达式来表示值。)
>>> print repr("Hello,world1")
'Hello,world1'
>>> print repr("Hello,world!")
'Hello,world!'
>>> print repr(8l)
8L
>>> print str("hello,world!")
hello,world!
>>> print str(8l)
8
-------------------------------------------------------------
what's your name?"jack"
hello,jack!
>>> raw_input("enter a number:")
enter a number:3
'3'
-------------------------------------------------------------
(一)长字符串
>>> print '''This is a very long string.
It continues here.
And it's not over yet.
"Hello,world!"
Still here.'''
This is a very long string.
It continues here.
And it's not over yet.
"Hello,world!"
Still here.
>>>
(二)原始字符串
在普通字符串中,反斜线有特殊的作用:它会转义,因此可以使用它在字符串中通常不能直接加入的内容。例如,换行符可以写为\n,并放入字符串中,如下:
>>> print "hello,\nworld!"
hello,
world!
以上有缺陷,例如关于到路径,就有问题了,如"C:\nowhere"去路径下,就会报错,解决法:
1、
>>> print "C:\nwhere"
C:
where
>>>
>>> print "C:\\nwhere"
C:\nwhere
2、以上1、方法比较繁琐,这种情况下,原始字符串就派上用场了。原始字符串不会把反斜线当作特殊字符。在原始字符串中输入的每个字符都会与书写的方式保持一致,如下:
>>> print r'C:\Program Files\python'
C:\Program Files\python
>>>
可以看到,原始字符串以r开头,但是若去C:\Program Files\python\下时也会报错,因为后面的\是转义字符,所以应该这样写:
>>> print r'C:\Program Files\python''\\'
C:\Program Files\python\
>>>
(三)Unicode字符串
>>> u'hello,world!'
u'hello,world!'
>>>
-------------------------------------------------------------------
一、索引
从0开始
二、分片
1、优雅的捷径
>>> numbers=[1,2,3,4,5,6,7,8,9,10]
>>> numbers[1:5]
[2, 3, 4, 5]
#捷径:
>>> numbers[-3:]
[8, 9, 10]
>>> numbers[:4]
[1, 2, 3, 4]
>>> numbers[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
分片示例:
>>> #http://www.something.com形式的URL进行分割
>>> url=raw_input('Please enter the URL:')
Please enter the URL:http://www.python.org
>>> domain=url[11:-4]
>>> print "Domain name:"+domain
Domain name:python
>>>
2、更大的步长(步长不能为0,但可以为负数)
>>> numbers[3:6:3]
[4]
>>> numbers[::4]
[1, 5, 9]
>>>
>>> numbers[8:3:-1]
[9, 8, 7, 6, 5]
>>>
3、序列相加
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 'Hello,'+'world!'
'Hello,world!'
#列表[]和字符串无法连接起来
>>> [1,2,3]+'world!'
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
[1,2,3]+'world!'
TypeError: can only concatenate list (not "str") to list
>>>
4、乘法
>>> 'python'*5
'pythonpythonpythonpythonpython'
>>> [42]*10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
>>>
#序列(字符串)乘法示例(打印盒子)注意!整数除法是"//"
sentence=raw_input("Sentence:")
screen_width=80
text_width=len(sentence)
box_width=text_width+6
left_margin=(screen_width-box_width)//2
print
print ''*left_margin+'+' +'-'*(box_width-2)+'+'
print ''*left_margin+'| '+' '*text_width +'|'
print ''*left_margin+'| '+ sentence +'|'
print ''*left_margin+'| '+' '*text_width +'|'
print ''*left_margin+'+' +'-'*(box_width-2)+'+'
print
>>> ================================ RESTART ================================
>>>
Sentence:he's a very naughty boy!
+----------------------------+
| |
| he's a very naughty boy!|
| |
+----------------------------+
>>>
5、成员资格:为了检查一个值是否在序列中,可以使用in运算符。条件真返回True,假返回False
>>> permissions='rw'
>>> 'w' in permissions
True
>>> 'x' in permissions
False
>>> users=['xiaozhou','zhangming','hello']
>>> raw_input('Enter your user name:') in users
Enter your user name:xiaozhou
True
>>>
6、长度、最小值、最大值
内建函数len、min、max非常有用。len函数返回序列中所包含的元素数量,min函数和max函数返回序列中最小值和最大值。
>>> sss=[3,5,7,31]
>>> len(sss)
4
>>> max(sss)
31
>>>
三、列表(list函数)
>>> list('Hello')
['H', 'e', 'l', 'l', 'o']
>>>
# 基本列表操作:
1、改变列表
>>> x=[1,1,1,1]
>>> x[1]=0
>>> x
[1, 0, 1, 1]
>>>
2、删除列表元素
>>> del x[2]
>>> x
[1, 0, 1]
>>>
3、分片赋值
>>> name=list('Hello')
>>> name
['H', 'e', 'l', 'l', 'o']
>>> name[2:]=list('ar')
>>> name
['H', 'e', 'a', 'r']
>>>
4、列表方法
(1)append方法用于在列表末尾追加心的对象。
>>> sss=[1,2,3]
>>> sss.append(4)
>>> sss
[1, 2, 3, 4]
(2) count方法统计某个元素在列表中出现的次数。
>>> ['to','be','not','to','be','com'].count('to')
2
>>> x=[[1,2],1,1,[2,1,[1,2]]]
>>> x.count(1)
2
>>> x.count([1,2])
1
>>>
(3)extend方法可以在列表的末尾一次性追加另一个序列中的多个值。即可以用新列表扩展原有的列表:
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
>>>
以上看起来像连接操作,其实不是,a+b则产生一个新的串,但a则没有变,extend是扩展。
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a+b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3]
>>>
有人说可以改成a=a+b,是否可以修改a列表值,这样可以但是代码的可读性就不如extend方法了。
(4)index方法用于从列表中找出某个值第一个匹配项的索引位置:
>>> name=['to','be','not','to','be','com']
>>> name.index("be")
1
>>>
(5)insert方法用于将对象插入到列表中:
>>> name=['to','be','not','to','be','com']
>>> name.insert(3,'three')
>>> name
['to', 'be', 'not', 'three', 'to', 'be', 'com']
>>>
(6)pop方法移除列表中的一个元素(默认是最后一个),并且返回该元素的值:
>>> name=['to','be','not','to','be','com']
>>> name.pop()
'com'
>>> name
['to', 'be', 'three', 'to', 'be']
>>>
>>> name.pop(2)
'not'
>>> name
['to', 'be', 'three', 'to', 'be', 'com']
>>>
注意!pop方法是唯一一个既能修改列表又返回元素值(除了None)的列表方法。
使用pop方法可以实现一种常见数据结构--栈(入栈push,出栈pop)python没有入栈,但可以用append代替。pop方法和append方法操作恰好相反:
>>> x=[1,2,3]
>>> x.append(x.pop()
>>> x
[1, 2, 3]
(7)remove方法用于移除列表中某个值的第一个匹配项:
>>> name=['to','be','not','to','be','com']
>>> name.remove('be')
>>> name
['to', 'three', 'to', 'be']
>>>
(8)reverse方法将列表中的元素反向存放。
>>> x=[1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]
>>>
(9)sort方法用于在原位置对列表进行排序。
>>> x=[4,6,2,1,7,9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
>>>
以上方法修改了原列表,若要不变原列表,则使用操作它的副本。(副本不能简单的使用y=x赋值,因为这样做就让x和y都指向同一个列表了)如下:
>>> x=[4,6,2,1,7,9]
>>> y=x[:]
>>> y.sort()
>>> y
[1, 2, 4, 6, 7, 9]
>>> x
[4, 6, 2, 1, 7, 9]
>>>
另一种获取已排序的列表副本的方法是,使用sorted函数
>>> x=[4,6,2,1,7,9]
>>> y=sorted(x)
>>> x
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]
>>>
(10)高级排序
如果希望元素能按照特定的方式进行排序(而不是sort函数默认的方式,即根据Python的默认排序规则按升序排列元素)那么可以使用compare(x,y)的形式自定义比较函数。compare(x,y)函数在x<y返回负数,x>y返回正数,x==y时返回0.定义好该函数之后,就可以提供给sort方法作为参数了。内建函数cmp提供了比较函数的默认实现方式:
>>> numbers=[5,2,9,7]
>>> numbers.sort(cmp)
>>> numbers
[2, 5, 7, 9]
>>>
sort方法函数有另外两个可选参数——key和reverse。
若要根据元素的长度进行排序,那么使用len作为键函数。
>>> x=['aardvark','abalone','acme','add','aerate']
>>> x.sort(key=len)
>>> x
['add', 'acme', 'aerate', 'abalone', 'aardvark']
>>>
reverse用来指明列表是否要进行反向排序。
>>> x=[4,6,2,1,7,9]
>>> x.sort(reverse=True)
>>> x
[9, 7, 6, 4, 2, 1]
>>>
------------------------------------------------------------------------------------------------------------
(四)元组()
>>> 1,2,3
(1, 2, 3)
>>> ()
()
>>> (2)
2
>>> (2,)
(2,)
>>>
1、tuple函数
功能与list函数基本一样:以一个序列作为参数并把它转换成元组,如果参数就是元组,那么该参数就会被原样返回:
>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple((1,2,3))
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>>
2、基本元组操作
>>> x=1,2,3
>>> x[1]
2
>>> x[0:2]
(1, 2)
>>>
-------------------------------------------------------------------------------------------------------------------
(五)格式化字符串(其实就是格式值替换被格式值中的%*内容。)%字符:标记转换说明符的开始。
>>> format="Hello,%s,%s enough for ya?"
>>> values=('world','hot')
>>> print format%values
Hello,world,hot enough for ya?
>>>
>>> '%s,plus %s equals %s' %(1,2,3)
'1,plus 2 equals 3'
>>>
注意!若使用列表代替元组,那么就会被解释为一个值,还有当要在格式化字符串里面包括百分号,那么使用%%
---------------------------------------------------------------------------------------------------------------------------
(六)字符串方法
1、find 方法查找字符串中子字符串第一次出现的索引位置值。
>>> 'with a moo-moo here,and a moo-moo there'.find('moo')
7
>>>
2、join 方法是非常重要的字符串方法,它是split方法的逆方法,用来在队列中添加元素:
>>> seq=[1,2,3,4,5]
>>> sep='+'
>>> sep.join(seq)#连接数字列表
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
sep.join(seq)#连接数字列表
TypeError: sequence item 0: expected string, int found
>>>
>>> seq=['1','2','3','4','5']
>>> sep='+'
>>> sep.join(seq)#连接数字串列表
'1+2+3+4+5'
>>> dirs='','user','bin','env'
>>> '/'.join(dirs)
'/user/bin/env'
>>> print 'C:'+'\\'.join(dirs)
C:\user\bin\env
>>>
3、lower 方法返回字符串的小写字母版。
>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
>>>
4、replace 方法返回某字符串的所有匹配项均被替换之后得到字符串。
>>> 'Trondheim Hammer Dance'.replace('Dance','U')
'Trondheim Hammer U'
>>>
5、split方法是一个非常重的字符串方法,它是join的逆方法,用来将字符串分割成序列。
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>>
>>> '/user/bin/env'.split('/')
['', 'user', 'bin', 'env']
>>>
6、strip 方法返回去除两侧(不包括内部)空格的字符串:
>>> ' trondheim hammer dance '.strip()
'trondheim hammer dance'
>>>
7、translate 方法和replace方法差不多,只不过translate方法只处理单个字符,它的优势在于可以同时进行多个处理,有时候比replace效率高得多。
string.maketrans(from,to) #创建用于转换的转换表
---------------------------------------------------------------------------------------------------------------------------
(七)当索引不好用时,字典:
1、创建字典和使用字典(字典中的键是唯一的,值并不唯一)
>>> phonebook={'Alice':'2341','Beth':'9102','Cecil':'0931','xiaozhou':'0938'}
>>>
2、dict函数
>>> items=[('name','Gumby'),('age',42)]
>>> d=dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'
>>>
以上也可以通过关键字参数来创建字典,如下:
>>> d=dict(name='Gumby',age=42)
>>> d
{'age': 42, 'name': 'Gumby'}
>>>
3、基本字典操作
其操作与序列基本相似。
(1)、clear 方法清除字典中所有的项。
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d.clear()
>>> d
{}
>>>
(2)、copy 方法返回一个具有相同键-值对的新字典
当在副本中替换值的时候,原始字典不受影响,但是,如果修改了某个值(原地修改,而不是替换),原始的字典也会改变。
(3)、fromkeys 方法使用给定的键建立新的字典,每个键默认对应的值为None.
>>> {}.fromkeys(['name'],'age')
{'name': 'age'}
(4)get 方法是个跟宽松的访问字典项的方法,一般来说,如果试图访问字典中不存在的项时会出错,而用get就不会。
>>> d={}
>>> print d['name']
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
print d['name']
KeyError: 'name'
>>> print d.get('name')
None
>>>
(5)、has_key 方法可以检查字典中是否含有给出的键。表达式d.has_key(k)相当于k in d。
>>> d={}
>>> d.has_key('name')
False
>>>
(6)、items和iteritems
items方法将所有的字典项以列表方式返回,iteritems方法作用大致相同,但是会返回一个迭代器对象而不是列表。
(7)、keys和iterkeys
keys方法将字典中的键以列表形式返回,而iterkeys则返回针对键的迭代器。
(8)、pop 方法用来获得对应于给定键的值,然后将这个键-值对从字典中移除。
>>> d={'x':1,'y':2}
>>> d.pop('x')
1
>>> d
{'y': 2}
>>>
(9)、popitem 方法类似于list.pop,后者会弹出列表的最后一个元素,但不同的是,popitem弹出随机的项,因为字典并没有“最好的元素”。
(10)、setdefault 方法在某种程度上类似于get方法。
(11)、update 方法可以利用一个字典项更新另外一个字典。
>>> d={'a':'123','b':'456','c':'789'}
>>> x={'b':'8888'}
>>> d.update(x)
>>> d
{'a': '123', 'c': '789', 'b': '8888'}
>>>
(12)、values和itervalues
values 方法以列表的形式返回字典中的值(itervalues返回值的迭代器)
|