[Python] Repeat the characters based on the preceding number in a string

Discussão em 'Python' iniciado por Stack, Março 19, 2025.

  1. Stack

    Stack Membro Participativo

    I am a beginner in python and this is how I approached to the solution: I have divided the string into two lists- number list and character list. And then I multiplied them. Is there any other better solution than this?

    def split_string(input_str):
    num_list =[]
    char_list =[]
    current_char =''
    result=''
    for i in range(len(input_str)):
    if input_str.isdigit():
    num_list .append(input_str)
    if current_char :
    char_list.append(current_char)
    current_char =''
    else:
    current_char+=input_str
    if current_char :
    char_list.append(current_char)
    for i in range(len(char_list)):
    result+= int(num_list)*char_list
    return result

    input_str = "1a2bc3efg"

    print(split_string(input_str))


    Example1:

    Input: 1a2bc3efg

    Output: abcbcefgefgefg

    Example2:

    Input: 3a4e

    Output: aaaeeee

    Continue reading...

Compartilhe esta Página