Заменить шаблон в питоне

1

Как заменить шаблон в строке

     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
  • 0
    Здесь есть несколько хороших ответов O (N), зачем принимать один из O (N ^ 2)?
  • 0
    @gnibbler Не могли бы вы пометить O (N)? Я не совсем привык смотреть на реальные примеры такого рода вещей. Здесь N ссылается на количество элементов ++ info ++?
Показать ещё 3 комментария
Теги:

8 ответов

4
Лучший ответ

Это должно быть достаточно простым:

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++)")]
  • 0
    +1 Коротко и просто - красиво сделано!
  • 0
    +1 для itertools.cycle
2
import string

decoded_str = " Name(++info++)Age(++info++)Adress of the emp(++info++)"
s = decoded_str.replace('++info++', '++info %s++')
s % tuple(i for i in string.ascii_lowercase[:s.count('%s')])
2

Вот довольно уродливое, но прагматичное решение:

import string

decoded_str = " Name(++info++)Age(++info++)Adress of the emp(++info++)"
letters = list(string.lowercase)
token = "(++info++)"
rep_token = "(++info %s++)"

i = 0
while (token in decoded_str):
    decoded_str = decoded_str.replace(token, rep_token % letters[i], 1)
    i += 1

print decoded_str
  • 0
    +1 для именованных переменных и читабельного кода.
  • 0
    Приятно...............
1
from itertools import izip
import string
decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)"
parts = iter(decoded_str.split("(++info++)"))
first_part = next(parts)
tags = iter(string.ascii_lowercase)
encoded_str=first_part+"".join("(++info %s++)%s"%x for x in izip(tags, parts))
print encoded_str
  • 0
    Спасибо за пример. Это показалось мне одной новой вещью и напомнило мне о пяти, которые я забыл.
1
import re, string

decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)"

sub_func=('(++info %s++)'%c for c in '.'+string.ascii_lowercase).send
sub_func(None)
print re.sub('\(\+\+info\+\+\)', sub_func, decoded_str)
1

Вот быстрый взлом для этого:

string=" Name(++info++)Age(++info++)Adress of the emp(++info++)"

def doit(s):
    import string
    allTheLetters = list(string.lowercase)
    i=0
    s2 = s.replace("++info++","++info "+allTheLetters[i]+"++",1)
    while (s2!=s):
        s=s2
        i=i+1
        s2 = s.replace("++info++","++info "+allTheLetters[i]+"++",1)
    return s

Обратите внимание, что производительность, вероятно, не очень велика.

0
decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)"

import re
for i, f in enumerate(re.findall(r"\(\+\+info\+\+\)",decoded_str)):
    decoded_str = re.sub(r"\(\+\+info\+\+\)","(++info %s++)"%chr(97+i),decoded_str,1)
print decoded_str
0
>>> import re
>>> rx = re.compile(r'\(\+\+info\+\+\)')
>>> s = "Name(++info++)Age(++info++)Adress of the emp(++info++)"
>>> atoz = iter("abcdefghijklmnopqrstuvwxyz")
>>> rx.sub(lambda m: '(++info ' + next(atoz) + '++)', s)
'Name(++info a++)Age(++info b++)Adress of the emp(++info c++)'

Ещё вопросы

Сообщество Overcoder
Наверх
Меню