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

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

最佳答案

这是一个简单的方法:

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

输出:DAAAAAAAAAAGGGABC

关于Python - 如何将字符串中的字符乘以字符后的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47246668/

相关文章:

python - pandas DataFrame 过滤器正则表达式

python - 使用 python 接收 icecast 元数据

python - 使用 "python -i"交互解释时如何重新加载我的 Python 源文件

python - 在 python 3 中应用 python 2 代码时遇到问题

python - Pandas 替换特定列上的值

python - 作为初始值的外键未传递给 django 中的 ModelForm

python - 运行 docker image 时在 python 中传递 url 作为参数

python - 如何使用内联 if 进行字典理解?

python - 子类化: Is it possible to override a property with a conventional attribute?

python - 在 python - flask - jinja2 模板中迭代多个列表