I have a line where the character ('@') should be replaced with characters from the list of one or more characters "in order" and "periodically". So, for example, I have
'ab@cde@@fghi@jk@lmno@@@p@qrs@tuvwxy@z'
and want
'ab1cde23fghi1jk2lmno312p3qrs1tuvwxy2z'
for replace_chars = ['1', '2', '3']
The problem is that in this example there is more @ in the line than I have substitutes for.
This is my attempt:
result = '' replace_chars = ['1', '2', '3'] string = 'ab@cde@@fghi@jk@lmno@@@p@qrs@tuvwxy@z' i = 0 for char in string: if char == '@': result += replace_chars[i] i += 1 else: result += char print(result)
but this only works, of course, if the source line has no more than three @, and otherwise I get an IndexError .
Edit: Thanks for the answers!
FirimaElda
source share