Python如何将字符串中的字符乘以ch之后的数字

2024-04-25 19:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

标题,例如我想把“A3G3A”变成“AAAGGGA”。 到目前为止我有这个:

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

Tags: in标题forstringlenifanyrange
3条回答

管理所有案例的最小纯python代码。

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

对于input="WA5OUH2!10"outputWAAAAAOUHH!!!!!!!!!!+'a'是因为输出延迟,所以在最后执行良好行为。

假设格式总是一个字母后跟一个整数,最后一个整数可能丢失:

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

假设格式可以是后跟整数的任何子字符串,整数可能超过一位,最后一个整数可能丢失:

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

这里有一个简单的方法:

string = 'A3G3A'

expanded = ''

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

print(expanded)

输出:AAAGGGA

它假定输入有效。它的限制是重复因子必须是一个数字,例如2-9。如果希望重复因子大于9,则必须对字符串执行稍微多一些的解析:

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

输出:daaaaaaaagggabc

相关问题 更多 >

    热门问题