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

Python从头开始替换字符串

  1. def nth_replace(s, old, new, occurrence):
  2. li = s.rsplit(old, occurrence)
  3. return new.join(li)
  4. str1 = "caars caars caars caars caars"
  5. str2 = nth_replace(str1, 'aa', 'a', 1)
  6. print(str2)
  7. str2 = nth_replace(str1, 'aa', 'a', 2)
  8. print(str2)
  9. str2 = nth_replace(str1, 'aa', 'a', 3)
  10. print(str2)

Output:

  1. caars caars caars caars cars
  2. caars caars caars cars cars
  3. caars caars cars cars cars

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