以下是 Python 代码实现:

s = "The D is a party."
s_list = s.split(" ")
for i in range(len(s_list)):
    if s_list[i] == "D":
        if i == 0 or i == len(s_list)-1 or not s_list[i-1].isalpha() or not s_list[i+1].isalpha():
            s_list[i] = "党"
s = " ".join(s_list)
print(s)

输出结果为:

The D is a party.

如果将字符串改为 "D is a member of the Democratic Party.",输出结果将为:

党 is a member of the Democratic Party.
python 把D替换成党 假如D字符前后是英文则不替换

原文地址: http://www.cveoy.top/t/topic/hfk8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录