替换python字符串中的任意字符

问题描述 投票:0回答:1

我正在尝试这样的事情:

data_01 = "This is an example string Item 03"
if data_01.find("Item %%") != -1:
            data_01 = data_01.replace("Item %%", "")
    

我需要删除“Item”之后的任何字符,因为data_01字符串并不总是“Item 03”,它可以是“Item 4”作为示例。

python string replace
1个回答
0
投票

希望这个“弗兰肯斯坦”解决方案能有所帮助。它通过查找

Item
然后查找第二组空格来提取“Item ...”形式的任何内容。

def remove_item_and_number(string: str) -> str:
    out = []
    index = string.find("Item")
    if index == -1:
        return string

    out.append(string[:index].strip())

    next_index = index + 4
    non_space_encontered = False
    for i in range(next_index, len(string)):
        if not non_space_encontered and string[i] == " ":
            continue
        else:
            non_space_encontered = True

        if string[i] == " ":
            out.append(string[i:])
            break

    return "".join(out).strip()


if __name__ == "__main__":
    test_cases = [
        "This is an example string Item 03",
        "Another item: Item 2, with a comma",
    ]

    for test_case in test_cases:
        print(remove_item_and_number(test_case))

# >> "This is an example string Item 03" -> "This is an example string"
# >> "Another item: Item 2, with a comma" -> "Another item: with a comma"
© www.soinside.com 2019 - 2024. All rights reserved.