【问题标题】:In python how to replace a substring in a string without using replace method and using join method?在python中如何在不使用replace方法和使用join方法的情况下替换字符串中的子字符串?
【发布时间】:2021-06-26 11:58:11
【问题描述】:

如何使用python中的.join方法或除replace()以外的任何其他方法将target_string中的replace_string替换为find_string

target_string="Maybe she's born with it. Maybe it's Maybelline."
find_string = "Maybe"
replace_string = "Perhaps"
def replace_all(target_string, find_string, replace_string):


replace_all(target_string, find_string, replace_string)

【问题讨论】:

    标签: python-3.x string join substring


    【解决方案1】:

    您可以使用str.splitstr.join。例如:

    target_string = "Maybe she's born with it. Maybe it's Maybelline."
    find_string = "Maybe"
    replace_string = "Perhaps"
    
    
    def replace_all(target_string, find_string, replace_string):
        while find_string in target_string:
            target_string = replace_string.join(target_string.split(find_string))
        return target_string
    
    
    print(replace_all(target_string, find_string, replace_string))
    

    打印:

    Perhaps she's born with it. Perhaps it's Perhapslline.
    

    【讨论】:

    • 非常感谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2016-01-27
    • 2023-03-14
    • 1970-01-01
    • 2011-05-10
    • 2014-03-03
    • 2015-07-18
    相关资源
    最近更新 更多