6-12. Strings.
(1)Create a function called findchr(), with the following declaration:
def findchr(string, char)
findchr() will look for character char in string and return the index of the first occurrence of char, or -1 if that char is not part of string. You cannot use string.*find() or string.*index() functions or methods.
(2)Create another function called rfindchr() that will find the last occurrence of a character in a string. Naturally this works similarly to findchr(), but it starts its search from the end of the input string.
(3)Create a third function called subchr() with the following declaration:
def subchr(string, origchar, newchar)
subchr() is similar to findchr() except that whenever origchar is found, it is replaced by newchar. The modified string is the return value.
1#!/usr/bin/env python
2#-*- coding:utf-8 -*-
3#$Id: p0612.py 140 2010-05-27 04:10:06Z xylz $
4
5'''
6This is a 'python' study plan for xylz.
7Copyright (C)2010 xylz (www.imxylz.info)
8'''
9
10
11def findchr(s,ch):
12 """
13 Look for character 'ch' in 's' and return the index of the first occurrence of 'ch', or -f if that 'ch' is not part of 's'
14 """
15 if s is None or len(s)==0: return -1
16 for i,c in enumerate(s):
17 if c == ch: return i
18 return -1
19
20def rfindchr(s,ch):
21 """
22 Look for character 'ch' in 's' and return the index of the last occurrence of 'ch', or -f if that 'ch' is not part of 's'
23 """
24 if s is None or len(s)==0: return -1
25 for i in range(len(s)-1,-1,-1):
26 if s[i] == ch: return i
27 return -1
28
29def subchr(s,oldch,newch):
30 """
31 Look for character 'oldch' in 'newch' and replace each 'oldch' with 'newch' and return the string modified.
32 """
33 if s is None or len(s)==0: return s
34 ret=[]
35 for c in s:
36 ret.append(c if c!=oldch else newch)
37 return ''.join(ret)
38
39
40if __name__ == '__main__':
41 assert 1 == findchr('Good','o')
42 try:
43 assert 0 == findchr('Good','x')
44 raise ValueError, 'Test fail.'
45 except AssertionError as e:
46 print e
47 assert 2 == rfindchr('Good','o')
48 assert 'Gxxd' == subchr('Good','o','x')
49
50
在此类的测试程序中,使用assert断言来测试正确性,如果测试失败会抛出一个AssertionError的异常。
©2009-2014 IMXYLZ
|求贤若渴