Skip to main content
 首页 » 编程设计

python之替换 python 中的模式

2025年05月04日10Leo_wl

如何将字符串中的模式替换为

     decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)" 
 
 The first pattern "(++info++)" needs to replaced with (++info a++) 
 The second pattern "(++info++)" needs to replaced with (++info b++) 
 The third pattern "(++info++)" needs to replaced with (++info c++) 
 If there many more then it should be replaced accordingly 

请您参考如下方法:

这应该很简单:

for character in range(ord('a'), ord('z')): 
    if "(++info++)" not in decoded_str: 
        break 
    decoded_str = decoded_str.replace("(++info++)", "(++info {0}++)".format(chr(character)), 1) 
 
print decoded_str 

它具有在“z”处停止的额外好处。如果你想环绕:

import itertools 
 
for character in itertools.cycle(range(ord('a'), ord('z'))): 
    if "(++info++)" not in decoded_str: 
        break 
    decoded_str = decoded_str.replace("(++info++)", "(++info {0}++)".format(chr(character)), 1) 
 
print decoded_str 

只是为了好玩,一行,O(n):

dstr = "".join(x + "(++info {0}++)".format(chr(y)) for x, y in zip(dstr.split("(++info++)"), range(ord('a'), ord('z'))))[:-len("(++info a++)")]