Home > Mobile >  Substitute * with (1) and increment the number each time
Substitute * with (1) and increment the number each time

Time:12-15

I'm new to Python and I need to do this:

I need to substitute in a string all the * with a (1) and the number has to increment in 1 each time. For example:

notes ("This is a note *; and this is another note *") Output: This is a note (1); and this is another note (2)

I'm trying this:

def notes (string):
    asterisco = "*"
    for asterisco in asterisco:
        numero = 1
        numero_str = str(numero)
        sustituto = "("   numero_str   ")"
        string = string.replace(asterisco, sustituto)
        numero  =1
    print (string)


notes("hola*** ")

But the output is: hola (1)(1)(1)

Any help?

Thanks! Joana.

I'm trying this:


def notes (string): asterisco = "*" for asterisco in asterisco: numero = 1 numero_str = str(numero) sustituto = "(" numero_str ")" string = string.replace(asterisco, sustituto) numero =1 print (string)

notes("hola*** ")


I expect this:

notes ("This is a note *; and this is another note *")
Output: This is a note (1); and this is another note (2)

CodePudding user response:

You might write the code splitting on an asterix, and then combine the splitted parts with a range based on the number of parts.

def notes(s):
    parts = s.split("*")
    if len(parts) == 1:
        return s
    return "".join([f"{x}({y})" for x, y in zip(parts, range(1, len(parts)))])


print(notes("This is a note *; and this is another note *"))
print(notes("This is a note *;"))
print(notes("This is a note"))

Output

This is a note (1); and this is another note (2)
This is a note (1)
This is a note
  • Related