Python implements the "replace" function

Implementing the "replace" function in Python

string1="aaa新年快乐bbb"
string2=string1.replace("新年快乐", "恭喜发财")
print(string2)
# aaa恭喜发财bbb

string3="aaa新年快乐bbb新年快乐ccc"
string4=string3.replace("新年快乐", "恭喜发财", 2)
print(string4)
# aaa恭喜发财bbb恭喜发财ccc

Implement batch replacement Replace
the replace function with a dictionary + custom function to achieve batch "one-to-one" replacement


# 保存映射关系的函数,函数的主要功能是通过字典实现的
def replace_city(city_name):
    return {
    
    
        "GUANGDONG":"广东省",
        "HEBEI":"河北省",
        "HUNAN":"湖南省",
        "HANGZHOU":"杭州市"
    }[city_name]

# 根据映射关系实现批量循环
def replace_multi(my_citys, replaced_string):
    for pinyin_city in my_citys:
        replaced_string = replaced_string.replace(
            pinyin_city,replace_city(pinyin_city))
    return replaced_string
    
# 哪些城市要替换
citys = ("GUANGDONG", "HUNAN")

# 需要替换的字符串
string1 = """
GUANGDONG,简称“粤”,中华人民共和国省级行政区,省会广州。
因古地名广信之东,故名“GUANGDONG”。位于南岭以南,南海之滨,
与香港、澳门、广西、HUNAN、江西及福建接壤,与海南隔海相望。"""

string2 = replace_multi(citys, string1)
print(string2)
# 广东省,简称“粤”,中华人民共和国省级行政区,省会广州。
# 因古地名广信之东,故名“广东省”。位于南岭以南,南海之滨,
# 与香港、澳门、广西、湖南省、江西及福建接壤,与海南隔海相望。

Use logical judgment + custom function to replace replace() function to achieve "many-to-one" replacement


age = 18
if age>0 and age<=6:
    value="少年"
    
elif age>7 and age<=18:
    value=青年"

elif age>19 and age<=65:
    value="中年"

else:
    value="老年"

Summarize

String replace() function;
use dictionary to do "one-to-one" mapping, and implement content replacement through dictionary-type key-value pairs;
use logical judgment to achieve "many-to-one" mapping, and replace the condition of if judgment with a successful match the result of.

The replacement operation needs to choose the appropriate method according to the form of the replaced content. The replace() function is more suitable for single replacement, the dictionary is suitable for "one-to-one" replacement, and the if logic judgment is suitable for replacing a range with a value.

In addition to flexibly mastering different replacement methods, I also recommend that you put dictionaries and logical judgments into custom functions, and you can directly reuse code when you encounter similar requirements.

Guess you like

Origin blog.csdn.net/david2000999/article/details/121503634