Python - 如何在字符后用字符串乘以字符串中的字符

时间:2017-11-12 07:54:48

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

7 个答案:

答案 0 :(得分:8)

这是一种简单的方法:

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

答案 1 :(得分:2)

假设格式始终是一个字母后跟一个整数,可能缺少最后一个整数:

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

答案 2 :(得分:1)

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

call adb.cmd ...

Private sub Sender() Dim A As String Dim B As String A = "text A" B = "text B" End Sub Private sub reciver() Msgbox = A Msgbox = B End Sub 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"output是在最后强制执行良好行为,因为输出会延迟。

答案 3 :(得分:0)

另一种方法可能是 -

class CustomComponent extends ConstraintLayout {
    public void init(Context context) {
        inflate(context, R.layout.wrapper, this);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        View child = getChildAt(1);
        removeView(child);
        ViewGroup wrapped= findViewById(R.id.wrapped);
        wrapped.addView(child);
    }
}

说明 -

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'

答案 4 :(得分:0)

使用*重复字符:

假设中继器的范围在[1,9]之间
private String userId = "";

答案 5 :(得分:0)

system

希望有帮助。如果您需要更多-请考虑搜索string = 'A3G3A' string.rjust(10, 'A')

答案 6 :(得分:0)

一线解决方案。假设数字在[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