几道Python的小习题
学习Python的道路漫漫,光看不练比较无聊。
找了个网页,上面有几道习题,无聊之余拿来练手,还有些乐趣。
是这里:http://www.cnblogs.com/belaliu/archive/2006/11/25/572140.html
注:习题后面贴的代码不一定是最优的。
大部分比较好解决,有点难度的是第4题做去除字符串内的空格的操作。
找了网上的解决方案,有这样的好做法:
stringReplace=lambda x:''.join(x.split(' '))
调用时只要stringReplace(myString)就行了。
相关文档:
源代码下载:下载地址在这里
# 026
aList = ['1','2','3','4']
aListCopy = aList # 其实,这里仅仅复制了一个引用
del aList[0]
print aList
print aListCopy # 两个引用指向了了同一个对象,所以打印结果一样
aListCopy = aList[:] # 这是复制整个对象的有效方法
del aList[0]
print aList
print aListCopy
......
# 027
toolName = 'Google'
if toolName.startswith('Go'):
print 'The tool\'s name starts with \"Go\".'
if 'oo' in toolName:
print 'The tool\'s name contains the stirng "oo".'
print toolName.find('gl') # 返回首次出现“gl”字符串的索引
if toolName.find('Baidu ......
源代码下载:下载地址在这里
# 029
aFile = file(r'C:\in.txt', 'r')
while True:
line = aFile.readline()
if len(line) == 0:
break
# end of if
print line,
# end of while
aFile.close()
output:
>>>
This is the first line.
This is the second line.
This is ......
# 040
import time
try:
f = file('040_Finally.py')
while True:
line = f.readline()
if len(line) == 0:
break
time.sleep(0.33)
print line,
# end of while
finally:
f.close()
print 'Closed the file.'
# end of try
output:
> ......