当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

在Python中从左右修剪指定数量的空格

  1. def trim(text, num_of_leading, num_of_trailing):
  2. text = list(text)
  3. for i in range(num_of_leading):
  4. if text[i] == " ":
  5. text[i] = ""
  6. else:
  7. break
  8. for i in range(1, num_of_trailing+1):
  9. if text[-i] == " ":
  10. text[-i] = ""
  11. else:
  12. break
  13. return ''.join(text)
  14. txt1 = " Candada "
  15. print(trim(txt1, 1, 1))
  16. print(trim(txt1, 2, 3))
  17. print(trim(txt1, 6, 8))

Output:

  1. Candada
  2. Candada
  3. Candada

该分类下的相关小册推荐: