Найти - Пользователи
Полная версия: metod str.replace()
Начало » Центр помощи » metod str.replace()
1
alex28746
Pomogite pozalujasta napisat funkciu kotoraja w storke symwolow OLD zamenajet na symwoly iz stroki NEW i wozwraszczajet uze izmenionnyj string.
Primer:
>>> rplstr(“U Ally jest kot, kot belyj”,“belyj”,“white”)
'U Ally jest kot,kot white'
#nelzia ispolzowat metod str.replace()
ZerG
stroka = "Some text"
def rep(stroka, data, after):
    s = stroka
    s = s.replace(data, after)
    return s
print rep(stroka, 'text', 'her')   
botinag
ZerG,
alex28746
#nelzia ispolzowat metod str.replace()

import re
def rplstr(text, old, new):
    t = list(text)
    olds = [x.start() for x in re.finditer(old, text)]
    for i in reversed(olds):
        t[i:i+len(old)] = new
    return ''.join(t)
>>> rplstr('cat-meow, dog-wuff, cat-meow', 'cat', 'dog')
'dog-meow, dog-wuff, dog-meow'
ZerG
чото я седня туплю;;;
terabayt
alex28746
def rplstr(s, old, new):
    i, l = s.find(old), len(old)
    while i + 1:
        s = s[:i] + new + s[i+l:]
        i = s.find(old)
    return s
botinag
при каждой итерации вычислять len(old), эт плохо
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB