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

如何在Python中替换字符串中的特定字符串实例

  1. def nth_replace(str,search,repl,index):
  2. split = str.split(search,index+1)
  3. if len(split)<=index+1:
  4. return str
  5. return search.join(split[:-1])+repl+split[-1]
  6. str1 = "caars caars caars"
  7. str2 = nth_replace(str1, 'aa', 'a', 1)
  8. print(str2)

Output:

  1. caars cars caars

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