The function I have to build is meant to replace digits in a string by (value of digit * next character).
So, foo = '2 hs4q q2w2 '
will become ' hsqqqq qww '
(mind the spaces)
Assumption - Digit can't be zero.
I fetched the (index,value) of digits and next char. Used that info to get the substrings I need to put back into the string:
foo = '2 hs4q q2w2 '
parameters=[(int(foo_list[b]),b+1) for b in range(len(foo_list)) if foo_list[b].isdigit()]
parameters # list of tuples (digit,charindex to be extended)
#[(2, 1), (4, 5), (2, 9), (2, 11)]
for p,i in parameters:
hoo=p*foo[i]
print (hoo,type(hoo))
#Out
<class 'str'> # Two spaces
qqqq <class 'str'>
ww <class 'str'>
<class 'str'> # Two spaces
How can I use all this info in a loop that works with similar strings? I understand strings are immutable, hence a new str object has to be created for every insert/replace. Plus the index values change as the loop runs.
Comments after solution -
Thank you all for four different kinds of solutions, here is a reference for anyone who hasn't used yield from, yield
- In practice, what are the main uses for the new “yield from” syntax in Python 3.3?