《Python程序设计》习题与答案 下载本文

x = input('Please input x:') x = eval(x)

if x<0 or x>=20: print(0) elif 0<=x<5: print(x) elif 5<=x<10: print(3*x-5) elif 10<=x<20: print(0.5*x-2)

第4章 字符串与正则表达式

4.1 假设有一段英文,其中有单独的字母“I”误写为“i”,请编写程序进行纠正。 答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。

1)不使用正则表达式

x = \x = x.replace('i ','I ') x = x.replace(' i ',' I ') print(x)

2)使用正则表达式

x = \import re

pattern = re.compile(r'(?:[^\\w]|\\b)i(?:[^\\w])') while True:

result = pattern.search(x) if result:

if result.start(0) != 0:

x = x[:result.start(0)+1]+'I'+x[result.end(0)-1:] else:

x = x[:result.start(0)]+'I'+x[result.end(0)-1:] else:

break print(x)

4.2 假设有一段英文,其中有单词中间的字母“i”误写为“I”,请编写程序进行纠正。 答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。

import re

x = \print(x)

pattern = re.compile(r'(?:[\\w])I(?:[\\w])') while True:

result = pattern.search(x) if result:

if result.start(0) != 0:

x = x[:result.start(0)+1]+'i'+x[result.end(0)-1:] else:

x = x[:result.start(0)]+'i'+x[result.end(0)-1:] else:

break print(x)

4.3 有一段英文文本,其中有单词连续重复了2次,编写程序检查重复的单词并只保留一个。例如文本内容为“This is is a desk.”,程序输出为“This is a desk.”

答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。

1)方法一

import re

x = 'This is a a desk.'

pattern = re.compile(r'\\b(\\w+)(\\s+\\1){1,}\\b') matchResult = pattern.search(x)

x = pattern.sub(matchResult.group(1),x) print(x) 2)方法二

x = 'This is a a desk.'

pattern = re.compile(r'(?P\\b\\w+\\b)\\s(?P=f)') matchResult = pattern.search(x)

x = x.replace(matchResult.group(0),matchResult.group(1))

4.4 简单解释Python的字符串驻留机制。 答:

Python支持字符串驻留机制,即:对于短字符串,将其赋值给多个不同的对象时,内存中只有一个副本,多个对象共享该副本。这一点不适用于长字符串,即长字符串不遵守驻留机制,下面的代码演示了短字符串和长字符串在这方面的区别。 >>> a = '1234' >>> b = '1234' >>> id(a) == id(b) True

>>> a = '1234'*50 >>> b = '1234'*50 >>> id(a) == id(b) False

4.5 编写程序,用户输入一段英文,然后输出这段英文中所有长度为3个字母的单词。 答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。

import re

x = input('Please input a string:')

pattern = re.compile(r'\\b[a-zA-Z]{3}\\b') print(pattern.findall(x))