Python批量替换字符串内容

问题描述

批量替换字符串内容

x: 原始字符串

old: 要替换的内容,可为 str , list

new: 新内容,可为 str , list , None

strip: 是否删除前后空格

不传新内容 new ,则要替换的内容 old 被删掉。




解决方案

from itertools import zip_longest


def replace(x, old, new=None, strip=False) -> str:
    '''批量替换字符串内容

    :param x: 原始字符串
    :param old: 要替换的内容,可为 `str` , `list`
    :param new: 新内容,可为 `str` , `list` , `None`
    :param strip: 是否删除前后空格

    >>> replace('10000阅读', old='阅读')
    '10000'
    >>> replace('文章10000阅读', old=['文章', '阅读'])
    '10000'
    >>> replace('10000阅读', old='阅读', new='点击')
    '10000点击'
    >>> replace('文章10000阅读', old=['文章', '阅读'], new=[None, '点击'])
    '10000点击'
    >>> replace('文章10000阅读', old=['文章', '阅读'], new=['', '点击'])
    '10000点击'
    >>> replace('文章10000阅读', old=['文章', '阅读'], new=['美文'])
    '美文10000'
    '''
    if not new:
        new = ''
    if isinstance(old, str):
        x = x.replace(old, new)
    if isinstance(old, list):
        for _old, _new in zip_longest(old, new, fillvalue=''):
            if _new == None:
                _new = ''
            x = x.replace(_old, _new)
    if strip:
        x = x.strip()
    return x




参考文献

  1. Python itertools——高效迭代

猜你喜欢

转载自blog.csdn.net/lly1122334/article/details/107386899