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.
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?
You can check if a character is a digit with str.isdigit
, if it is then cast it to an int
and multiply it with the next character. This logic can be written as a generator given to str.join
.
def expand_string(s):
return ''.join([(int(c) - 1) * s[i+1] if c.isdigit() else c for i, c in enumerate(s)])
foo = '2 hs4q q2w2 '
print(expand_string(foo)) # ' hsqqqq qww '
Although, the above fails for a string with multiple digit number such as f10o'
.
If you also want to consider numbers with multiple digits, you can write a generator function that groups digits together using itertools.groupby
.
from itertools import groupby
def group_digits(s):
for isdigit, group in groupby(s, str.isdigit):
yield from [''.join(group)] if isdigit else group
def expand_string(s):
s = list(group_digits(s))
return ''.join((int(c) - 1) * s[i+1] if c.isdigit() else c for i, c in enumerate(s))
foo = 'f10o'
print(expand_string(foo)) # 'foooooooooo'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With