11

Title, for example I want to make 'A3G3A' into 'AAAGGGA'. I have this so far:

if any(i.isdigit() for i in string):
    for i in range(0, len(string)):
        if string[i].isdigit():
             (i am lost after this)

8 Answers 8

10

Here's a simplistic approach:

string = 'A3G3A'

expanded = ''

for character in string:
    if character.isdigit():
        expanded += expanded[-1] * (int(character) - 1)
    else:
        expanded += character

print(expanded)

OUTPUT: AAAGGGA

It assumes valid input. It's limitation is that the repetition factor has to be a single digit, e.g. 2 - 9. If we want repetition factors greater than 9, we have to do slightly more parsing of the string:

from itertools import groupby

groups = groupby('DA10G3ABC', str.isdigit)

expanded = []

for is_numeric, characters in groups:

    if is_numeric:
        expanded.append(expanded[-1] * (int(''.join(characters)) - 1))
    else:
        expanded.extend(characters)

print(''.join(expanded))

OUTPUT: DAAAAAAAAAAGGGABC

6
  • itertools.groupby - it will generate iterators containing {A,10,G,3,ABC} ? based on true/false flip of isdigit? Nov 12, 2017 at 8:43
  • 1
    @PatrickArtner, yes but it will also include the result of isdigit() along with the iterators so you also know what you're looking at! Conceptually, something like: [(False, ['A']), (True, ['1', '0']), (False, ['G']), (True, ['3']), (False, ['A', 'B', 'C'])]
    – cdlane
    Nov 12, 2017 at 8:48
  • It is "better" to create an empty list where you add text and then glue it together with join, as your solution keeps creating new variables (+= with strings). I took the liberty and made edits +1.
    – Anton vBR
    Nov 12, 2017 at 8:54
  • @AntonvBR, you broke my code please rollback your edit! Consider the string 'ABC3' which goes to 'ABCCC' but in your mod it goest to 'ABCABCABC'. It was just an example, it didn't need added efficiency.
    – cdlane
    Nov 12, 2017 at 8:56
  • 1
    @AntonvBR, no, I've an alternative fix.
    – cdlane
    Nov 12, 2017 at 9:01
2

Assuming that the format is always a letter followed by an integer, with the last integer possibly missing:

>>> from itertools import izip_longest
>>> s = 'A3G3A'
>>> ''.join(c*int(i) for c, i in izip_longest(*[iter(s)]*2, fillvalue=1))
'AAAGGGA'

Assuming that the format can be any substring followed by an integer, with the integer possibly longer than one digit and the last integer possibly missing:

>>> from itertools import izip_longest
>>> import re
>>> s = 'AB10GY3ABC'
>>> sp = re.split('(\d+)', s)
>>> ''.join(c*int(i) for c, i in izip_longest(*[iter(sp)]*2, fillvalue=1))
'ABABABABABABABABABABGYGYGYABC'
1

A minimal pure python code which manage all cases.

output = ''
n = ''
c = ''
for x in input + 'a':
    if x.isdigit():
        n += x
    else:
        if n == '': 
            n = '1'
        output = output + c*int(n)
        n = ''
        c = x

with input="WA5OUH2!10", output is WAAAAAOUHH!!!!!!!!!!. +'a' is to enforce the good behaviour at the end, because output is delayed.

2
  • Nice one, but I'd also use list [] for output, append and glue with join. And declaring variables on same row and not using row break for if statements creates lower readability in my opinion.
    – Anton vBR
    Nov 12, 2017 at 10:52
  • input is a builtin function, you should avoid using it as a variable name
    – yosemite_k
    Nov 20, 2017 at 1:54
0

Another approach could be -

import re
input_string = 'A3G3A'
alphabets = re.findall('[A-Z]', input_string) # List of all alphabets - ['A', 'G', 'A']
digits = re.findall('[0-9]+', input_string) # List of all numbers - ['3', '3']
final_output = "".join([alphabets[i]*int(digits[i]) for i in range(0, len(alphabets)-1)]) + alphabets[-1] 
#  This expression repeats each letter by the number next to it ( Except for the last letter ), joins the list of strings into a single string, and appends the last character
#  final_output - 'AAAGGGA'

Explanation -

In [31]: alphabets # List of alphabets in the string
Out[31]: ['A', 'G', 'A']

In [32]: digits  # List of numbers in the string ( Including numbers more than one digit)
Out[32]: ['3', '3']

In [33]: list_of_strings = [alphabets[i]*int(digits[i]) for i in range(0, len(alphabets)-1)]  # List of strings after repetition

In [34]: list_of_strings
Out[34]: ['AAA', 'GGG']

In [35]: joined_string = "".join(list_of_strings) # Joined list of strings

In [36]: joined_string
Out[36]: 'AAAGGG'

In [38]: final_output = joined_string + input_string[-1] # Append last character of the string

In [39]: final_output
Out[39]: 'AAAGGGA'
0

using the * to repeat the characters:

assumption repeater range between [1,9]
q = 'A3G3A'
try:
    int(q[-1]) # check if it ends with digit
except:
    q = q+'1' # repeat only once
"".join([list(q)[i]*int(list(q)[i+1]) for i in range(0,len(q),2)])
0

One line solution. Assuming numbers in the range [0, 9].

>>> s = 'A3G3A'
>>> s = ''.join(s[i] if not s[i].isdigit() else s[i-1]*(int(s[i])-1) for i in range(0, len(s)))
>>> print(s)
AAAGGGA
0

Embrace regex! This finds all occurrences of the pattern non-digit character followed by non-negative integer (any number of digits) and replaces that substring with that many of the character.

import re
re.sub(r'(\D)(\d+)', lambda m: m.group(1) * int(m.group(2)), 'A3G3A')
0

This can be solved by numpy:

import numpy as np

x = 'A3G3A'

if not x[-1].isdigit():
    x += '1'

letters = list(x[::2])
times = list(map(int,x[1::2]))
lst = ''.join(np.repeat(letters, times))

#output
'AAAGGGA'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.