简体   繁体   English

将 * 替换为 (1) 并每次递增数字

[英]Substitute * with (1) and increment the number each time

I'm new to Python and I need to do this:我是 Python 的新手,我需要这样做:

I need to substitute in a string all the * with a (1) and the number has to increment in 1 each time.我需要用 (1) 替换字符串中的所有 *,并且数字每次都必须递增 1。 For example:例如:

notes ("This is a note *; and this is another note *") Output: This is a note (1); notes ("This is a note *; and this is another note *") Output: 这是一张便条 (1); and this is another note (2)这是另一张纸条 (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)但是 output 是: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) def notes (string): asterisco = "*" for asterisco in asterisco: numero = 1 numero_str = str(numero) sustituto = "(" + numero_str + ")" string = string.replace(asterisco, sustituto) numero +=1打印(字符串)

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)

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 Output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM