python基础学习笔记(三)

 

字符串基本操作

  所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最小值和最大值)对字符串同样适用,前面已经讲述的这些操作。但是,请注意字符串都是不可变的。

 

字符串的方法:

字符串从string 模块中“继承”了很多方法,这里只介绍一些特别有用的。

 

1find 

find 方法可以在一个较长的字符串中查找子字符串。它返回子串所在位置的最左端索引。如果没有找到则返回-1.

复制代码
>>> 'with a moo-moo here. and a moo-moo ther'.find('moo')
7
>>> title = "Monty Pyhon's Flying Circus"
>>> title.find('Monty')
0
>>> title.find('Python')
-1
复制代码

2、join

join 方法是非常重要的字符串方法,它是split方法的逆方法,用来在队列中添加元素:

复制代码
>>> seq = ['1','2','3','4','5']
>>> sep = '+'
>>> sep.join(seq)
'1+2+3+4+5'
>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print 'C:' + '\\'.join(dirs)
C:\usr\bin\env
复制代码

3、lower

lower 方法返回字符串的小写字母版。

如果想要编写“不区分大小写”的代码的话,那么这个方法就派上用场了-----代码会忽略大小写状态。

>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'

4、replace 

replace 方法返回某字符串的所有匹配项均被替换之后得到字符串。

>>> 'This is a test'.replace('is','eez')
'Theez eez a test'

如果,你使用过文字处理工具里的“查找并替换”功能的话,就不会质疑这个方法的用处了。

 

5、split

这是一个非常重要的方法,它是join的逆方法,用来将字符串分割成序列。

复制代码
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'using the default'.split()
['using', 'the', 'default']
复制代码

6、strip 

strip 方法返回去除两侧(不包含内部)空格的字符串:

>>> '      internal white space is kept    '.strip()
'internal white space is kept'

 

 

字典

 

字典的使用

现实中的字段及在python中的字段都进行了构建,从而可以轻松查到某个特定的词语(键),从而找到它的意义(值)。

某些情况下,字典比列表更加适用:

#  表征游戏棋盘的状态,每个键都是由坐标值组成的元组;

#  存储文件修改次数,用文件名作为键; 

#  数字电话/地址本

 

创建一个人名列表,以及四位的分机号码:

>>> names = ['zhangsan','lisi','wangwu','sunliu']
>>> numbers = ['2313','9102','3158','4326']
#通过下下方法查询
>>> numbers[names.index('zhangsan')]
'2313'

 

创建和使用字典

字典可以通过下面方式创建

>>> phonebook = {'zhangsai':'2313','lisi':'9102','wangwu':'3158'}

字典由多个键及与其对应的值构成,在上例中,名字是键,电话号码是值。

 

dict函数

可以用dict 函数,通过其他映射(比如其他字典)或(键,值)这样的序列对建立字典。

复制代码
>>> items = [('name','gumby'),('age',42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'gumby'}
>>> d['name']
'gumby'
复制代码

dict函数也可以通过关键字参数来创建字典,如下例所示:

>>> d = dict(name ='gumby', age=42)
>>> d
{'age': 42, 'name': 'gumby'}

 

字典示例:

复制代码
#简单数据库

#使用人名作为键的字典,每个人用另一个字典表示,其键‘phone’和‘addr’分别表示他们的电话号和地址,

people ={
    'zhangsan':{
        'phone':'2341',
        'addr':'foo drive 23'
    },
    'lisi':{
        'phone':'9102',
        'addr':'bar street 42'
        },
   'wangwu':{
        'phone':'3158',
        'addr':'baz avenue 90'
        }
    }

#针对电话号码和地址使用的描述性标签,会在打印输出的时候用到

labels = {
    'phone':'phone number',
    'addr':'address'
    }
name = raw_input('Name:')

#查找电话号码还是地址? 使用正确的键:
request = raw_input('phone number(p) or address (a)?')
#使用正确的键:
if request == 'p':key = 'phone'
if request == 'a':key = 'addr'

#如果名字是字典中的有效键才打印信息:
if name in people: print "%s's %s is %s." %(name, labels[key], people[name][key])

------------------------
#输入内容
>>> 
Name:zhangsan
phone number(p) or address (a)?p
#打印结果
zhangsan's phone number is 2341.
复制代码

 

 

学到这里已经很不耐烦了,前面的数据结构什么的看起来都挺好,但还是没法用它们做什么实际的事。

 

基本语句的更多用法


 

使用逗号输出

>>> print 'age:',25
age: 25

如果想要同时输出文本和变量值,却又不希望使用字符串格式化的话,那这个特性就非常有用了:

>>> name = 'chongshi'
>>> salutation = 'Mr'
>>> greeting = 'Hello.'
>>> print greeting,salutation,name
Hello. Mr chongshi

 

 

模块导入函数

从模块导入函数的时候,可以使用

import somemodule

或者

form somemodule immport  somefunction

或者

from somemodule import somefunction.anotherfunction.yetanotherfunction

或者

from somemodule import *  

最后一个版本只有确定自己想要从给定的模块导入所有功能进。

如果两个模块都有open函数,可以像下面这样使用函数:

module.open(...)

module.open(...)

当然还有别的选择:可以在语句末尾增加一个as子句,在该子句后给出名字。

复制代码
>>> import math as foobar   #为整个模块提供别名
>>> foobar.sqrt(4)
2.0
>>> from math import sqrt as foobar  #为函数提供别名
>>> foobar(4)
2.0
复制代码

 

赋值语句

序列解包

复制代码
>>> x,y,z = 1,2,3
>>> print x,y,z
1 2 3
>>> x,y=y,x
>>> print x,y,z
2 1 3
复制代码

可以获取或删除字典中任意的键-值对,可以使用popitem

复制代码
>>> scoundrel ={'name':'robin','girlfriend':'marion'}
>>> key,value = scoundrel.popitem()
>>> key
'name'
>>> value
'robin'
复制代码

链式赋值

链式赋值是将同一个值赋给多个变量的捷径。

复制代码
>>> x = y = 42
# 同下效果:
>>> y = 42
>>> x = y
>>> x
42
复制代码

增理赋值

>>> x = 2
>>> x += 1  #(x=x+1)
>>> x *= 2  #(x=x*2)
>>> x
6

 

 

控制语句


 if 语句:

复制代码
name = raw_input('what is your name?')
if name.endswith('chongshi'):
    print 'hello.mr.chongshi'
#输入
>>> 
what is your name?chongshi  #这里输入错误将没有任何结果,因为程序不健壮
#输出
hello.mr.chongshi
复制代码

 

else子句

复制代码
name = raw_input('what is your name?')
if name.endswith('chongshi'):
    print 'hello.mr.chongshi'
else:
  print 'hello,strager'
#输入
>>> 
what is your name?hh  #这里输和错误
#输出
hello,strager
复制代码

 

elif 子句

它是“else if”的简写

复制代码
num = input('enter a numer:')
if num > 0:
    print 'the numer is positive'
elif num < 0:
    print 'the number is negative'
else:
  print 'the nuber is zero'
#输入
>>> 
enter a numer:-1
#输出
the number is negative
复制代码

 

嵌套

下面看一下if嵌套的例子(python是以缩进表示换行的)

复制代码
name = raw_input('what is your name?')
if name.endswith('zhangsan'):
    if name.startswith('mr.'):
        print 'hello.mr.zhangsan'
    elif name.startswith('mrs.'):
        print 'hello.mrs.zhangsan'
    else:
        print 'hello.zhangsan'
else:
    print 'hello.stranger'
复制代码

  如果输入的是“mr.zhangsan”输出第一个print的内容;输入mrs.zhangshan,输出第二个print的内容;如果输入“zhangsan,输出第三个print的内容;如果输入的是别的什么名,则输出的将是最后一个结果(hello.stranger

 

断言

如果需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert 语句可以在程序中设置检查点。

复制代码
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100 , 'the age must be realistic'

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    assert 0 < age < 100 , 'the age must be realistic'
AssertionError: the age must be realistic
复制代码

 

 

循环语句


 打印1100的数(while循环)

复制代码
x= 1
while x <= 100:
    print x
  x += 1
#输出
1
2
3
4
.
.
100
复制代码

再看下面的例子(while循环),用一循环保证用户名字的输入:

复制代码
name = ''
while not name:
    name = raw_input('please enter your name:')
print 'hello.%s!' %name
#输入
>>> 
please enter your name:huhu
#输出
hello.huhu!
复制代码

打印1100的数(for 循环)

复制代码
for number in range(1,101):
  print number
#输出
1
2
3
4
.
.
100
复制代码

是不是比while 循环更简洁,但根据我们以往学习其它语言的经验,while的例子更容易理解。

 

一个简单for 语句就能循环字典的所有键:

复制代码
d = {'x':1,'y':2,'z':3}
for key in d:
  print key,'corresponds to',d[key]
#输出
>>> 
y corresponds to 2
x corresponds to 1
z corresponds to 3
复制代码

 

break语句

break 用来结束循环,假设找100以内最大平方数,那么程序可以从100往下迭代到0,步长为-1

复制代码
from math import sqrt
for n in range(99,0,-1):
    root = sqrt(n)
    if root == int(root):
        print n
        break
#输出
>>> 
81
复制代码

 

continue 语句

continue结束当前的迭代,“跳”到下一轮循环执行。

复制代码
while True:
    s=raw_input('enter something:')
    if s == 'quit':
        break
    if len(s) < 3:
        continue
  print 'Input is of sufficient length'
#输入
>>> 
enter something:huzhiheng  #输入长度大于3,提示信息
Input is of sufficient length
enter something:ha        #输入长度小于3,要求重输
enter something:hah       #输入长度等于3,提示信息
Input is of sufficient length
enter something:quit       #输入内容等于quit,结果
复制代码

 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值