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)
In python, to multiply number, we will use the asterisk character ” * ” to multiply number.
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.
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.
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.
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
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