Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to multiply characters in string by number after character

Tags:

python

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)
like image 301
user8927025 Avatar asked Nov 12 '17 07:11

user8927025


People also ask

How to multiply number in Python?

In python, to multiply number, we will use the asterisk character ” * ” to multiply number.

How do you replace all occurrences of a character in Python?

Replace all occurrences of a character in a string To replace all the occurrences of a character with a new character, we simply have to pass the old character and the new character as input to the replace() method when it is invoked on the string. You can observe this in the following example.

How do I split a string between characters in Python?

The Python standard library comes with a function for splitting strings: the split () function. This function can be used to split strings between characters. The split () function takes two parameters. The first is called the separator and it determines which character is used to split the string.

How to eliminate characters at the end of a string in Python?

Use strip () function can eliminate some characters that you don't want, for example: a = 'This is my string x00x00x00' b = a.strip ('x00') # or you can use rstrip () to eliminate characters at the end of the string print (b) You will get This is my string as the output.


1 Answers

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

like image 125
cdlane Avatar answered Mar 26 '23 12:03

cdlane