python自定义一个字符串替换的函数

2022-03-11 00:00:00 字符串 自定义 替换

python信息替换演示代码,最多支持9个参数的信息替换,在字符串内使用数字作为占位符,然后对指定数字进行相应的替换操作。

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/21
功能描述:python自定义一个字符串替换的函数
"""
Escape = "^"


def subst(Msg, *Args):
    """substitutes Args into Msg."""
    Result = ""
    while True:
        Items = Msg.split(Escape, 1)
        Result += Items[0]
        if len(Items) == 1 or len(Items[1]) == 0:
            break
        Msg = Items[1]
        (Ch, Msg) = (Msg[:1], Msg[1:])
        if Ch == Escape:
            Result += Escape
        elif Ch >= "0" and Ch <= "9":
            Result += Args[ord(Ch) - ord("0")]
    return Result

print(subst("the ^0 ^1", "red", "ball"))
# 输出结果:“the red ball”

以上代码在Python3.9环境下测试通过

相关文章