Функция sub в regex может принимать функцию в качестве аргумента repl.
📄 Из документации:
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
То есть для каждого совпадения будет вызвана функция для вычисления замены вместо замены на одну и ту же строку для всех совпадений.
Иными словами, для замены разных совпадений на разные строки не потребуется запускать re.sub() много раз для каждой строки замены. Достаточно определить функцию, которая вернёт строку для каждого из совпадений.
Описание слишком запутанное🤔, давайте лучше рассмотрим на простом примере:
Создаем карту замены. То есть какие строки на какие требуется менять.
remap = {
'раз': '1',
'два': '2',
'три': '3',
'четыре': '4',
'пять': '5',
}
Пишем функцию поиска строки для замены. Единственным аргументом будет объект re.Match.
Используя данные этого объекта мы вычисляем замену on-the-fly!
def get_str(match: re.Match):
word = match.group(1)
return remap.get(word.lower()) or word
Пример текста.
text = '''Раз Два Три Четыре Пять
Вместе будем мы считать
Пять Четыре Три Два Раз
Мы считать научим вас
'''
Теперь запускаем re.sub и вместо строки замены (repl) подаём имя функции.
(Данный паттерн ищет отдельные слова в тексте)
>>> print(re.sub(r'(\w+)', get_str, text))
1 2 3 4 5
Вместе будем мы считать
5 4 3 2 1
Мы считать научим вас
Думаю, достаточно наглядно 🤓
#libs#regex
Acne Studios Spring 2023 on how to wear:
- lace with spikes
- chiffon with rough leather
- torn jersey with flounces
- chapped skin with floral choker
- jeans to the neckline (for those who missed the high waist 😂)
-bows instead of a bodice
- denim vest with sheer skirts
And use the bag as a means of self-defense 😉
#fashionweek
And I have for you a new batch of fresh street shot by myself before the Elisabetta Franchi Spring 2023 show.
Minis, catsuits, heels, over the knee boots, hats, maxi flowers, slits and sexy in the truest sense of the Italians.
#fashionweek
Fendi delighted everyone who bought green clothes last year and continued this grassy extravaganza in the Spring 2023 collection.
Handbags, slippers, boots, and even total-green 💚 Delicate pistachio and fresh mint were a plus to the herbal one. Honestly, it reminds me a little of the best times at Bottega. There are fluffy mules, a lot of knitwear, elongated sleeves, and shaggy textures. And from the special, I liked the delicate asymmetry and side slits on the sleeves and skirts.
#fashionweek
Heading to NY for fashion week? 😉
Beautiful Carolina Herrera Spring 2023 with its already signature stripe 🖤 paired with a millefleur.
Large textile flowers were added to the tiny floral print, gorgeous flowered textile boots and sandals, clear reception of accent printed accessories - a clutch or a belt, a mix of flowers of different colors. And, according to tradition, many flying fabrics, ruffles, voluminous sleeves - in general, everything we expect from the spring collection.
#fashionweek
Rings on the toes, of course, are not new and, frankly, not the most convenient accessory, but they convey the atmosphere of summer and relaxation perfectly. At Etro Spring 2023 Menswear, rings were used with pajama sets, linen shorts and trousers, classic blue denim, and even a summery white suit.
Although the show was for men, the idea is agender, so let's try!
#fashionweek
The first eco-activist among brands is Stella McCartney, in her case, these are not empty words. Grape cake, eco-leather from the root structure of mushrooms, and many more eco-materials are in the Resort 2023 collection.
Particular attention (as always) in the collection is paid to:
- prints (mushrooms🍄, stripes, animals🐯🐄🦜 and animalistic)
- textures, the variety of which is great
- shapes (slits, fringes, the effect of ruggedness and perforation, the latter are generally given the central place of this collection, and the perforations are not on leather but cotton).
The lookbook was filmed on an Italian farm❤️
#fashionweek
The Fendace collaboration went on sale today.
If you look at the details separately, I like it: a cap with the Fendi logo, pins on the dress, the idea of a branded lining is not new, but it also looks good - in general, it’s not bad separately, but all together - for an amateur🙈 The video fully conveys the nature of the collection 😉
#fashionweek
Well, for those who have not yet had time to consider, those very crazy options from the Loewe Fall 2022 show that I spoke about above are also attached👆🏼
#fashionweek
In addition, to cringe sausages/balloons, car dresses, lip stories, the Loewe Fall 2022 show also featured leather dresses frozen in motion, made in the same technique as the already legendary Zendaya dress. Sits like a glove 👌🏼 - literally and figuratively.
#fashionweek
A "talking" screensaver at Alexander McQueen Fall 2022 show, piles of mulch, peat smell, birds chirping, and insect sounds awaited guests before being shown the collection at a warehouse in Brooklyn, New York. And the main theme of the collection is mycelium.
In the center of the collection there is bright mushroom embroidery and silk fringe, protruding knitted threads, which just imitated mycelium. But there were also less conceptual and more brand-specific rough leather, taffeta, blurry prints, X-shaped silhouettes.
#fashionweek
Lively and positive backstage from Jacquemus SS 2022, where you can see almost more than the show itself.
More details about the show were discussed a few days ago here.
#fashionweek
I reviewed the Jil Sander Fall 2022 collection. Based on the experience of past years I am sure that it will be taken apart for details, what you should pay attention to:
- capes, dresses, and cape blouses - the royal vibe continues its procession
- very minimalist bows - infantilism made its way even here
- lots of vest coats are my special love which is perfect for styling
- long gloves - they have been talked about many times, just another reminder
- caps on the head - a headdress that conquers our heads in the literal and figurative sense
- "knitted" fur - another eco-friendly solution after the mass rejection of natural fur
- Chelsea with metal trim - the harsh realities of the modern world
- large collars are a signature detail of the brand, which is only getting bigger.
#fashionweek