Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string elements, using their index, by a list of strings

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?

like image 459
pyeR_biz Avatar asked Jan 28 '23 01:01

pyeR_biz


1 Answers

Single digit numbers

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.

Code

def expand_string(s):
    return ''.join([(int(c) - 1) * s[i+1] if c.isdigit() else c for i, c in enumerate(s)])

Example

foo = '2 hs4q q2w2 '
print(expand_string(foo)) # '  hsqqqq qww  '

Although, the above fails for a string with multiple digit number such as f10o'.

Multiple digits numbers

If you also want to consider numbers with multiple digits, you can write a generator function that groups digits together using itertools.groupby.

Code

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))

Example

foo = 'f10o'
print(expand_string(foo)) # 'foooooooooo'
like image 187
Olivier Melançon Avatar answered Jan 30 '23 15:01

Olivier Melançon