6–6. 字符串.创建一个 string.strip()的替代函数:接受一个字符串,去掉它前面和后面的 空格(如果使用 string.*strip()函数那本练习就没有意义了)

 1 'Take a string and remove all leading and trailing whitespace'
 2 
 3 def newStrip(str):
 4     'delete blanks around a string'
 5     _end = len(str)
 6     _start = 0
 7     
 8     # delete the blanks at the beginning of the string
 9     for i in range(_end):
10         if str[i] != ' ':
11             _start = i
12             break              
13     else:
14         print 'invalid: The string is a blank string.'     # if the string is a 
15         _blank = True                                      # blank string
16         
17     
18     # delete the blanks in the end of the string
19     for i in range(-1, _start - _end, -1):
20         if str[i] != ' ':
21             _end = _end + i
22             break      
23     if not _blank:
24         print '-' + str[_start: _end] + '-'   # print '-' make sure the function work
25 
26 # test
27 if __name__ == '__main__':
28     newStrip(raw_input('Enter a string: '))

更多相关文章

  1. 创建单独的函数而不是一个大的缓慢处理时间?
  2. 用于搜索和替换大字符串的最快Python方法
  3. python cookboo 文件与IO 函数
  4. 在Python中强制使用函数参数类型?
  5. Python(名称空间、函数嵌套、函数对象)
  6. python 字符串操作
  7. python中函数参数传递的几种方法
  8. python函数篇0-2
  9. Python的范围函数如何工作?

随机推荐

  1. android4.0.4 系统默认值的修改
  2. 添加/修改子项的Firebase通知
  3. android MPChart图标使用详解
  4. 如何在 android 中转换为 'file:///stora
  5. Android SDK更新以及ADT更新出现问题的解
  6. Ubuntu Android/Sdk/build-tools/23.0.3/
  7. 如何执行删除请求而不返回类型或回调?(改
  8. 小米1出现的资源文件找不到问题!
  9. Android获取WIFI状态下的IP地址以及MAC地
  10. 从Wordpress API JSON响应反序列化嵌套的