Sep-22-2017, 03:20 PM
Use the third parameter to
str.replace
.>>> help(str.replace) Help on method_descriptor: replace(...) S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
>>> line = "1_1__" * 20 >>> line '1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__' >>> line.replace("1", "2") '2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__2_2__' >>> line.replace("1", "2", 10) '2_2__2_2__2_2__2_2__2_2__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__' >>> line.replace("1", "2", 10).replace("1", "3", 10) '2_2__2_2__2_2__2_2__2_2__3_3__3_3__3_3__3_3__3_3__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__1_1__'