Search for a word by letter, and replace the letter

You need to find all the words with the letter "в" in the word list, and replace the letter "в" with the letter "а" in all the words. How to do this, without breaking each word into letters and replacing by index. Example:

Entrance:

a=['рука', 'нож', 'ведро', 'Неаполь', 'Виктория', 'материк']

Output:

a=['рука', 'нож', 'аедро', 'Неаполь', 'аиктория', 'материк']
Author: MaxU, 2017-01-24

3 answers

For the list:

import re

In [143]: print(a)
['рука', 'нож', 'ведро', 'Неаполь', 'Виктория', 'материк', 'бровь']

In [144]: new = [re.sub(r'^в', r'а', word, flags=re.U|re.I) for word in a]

In [145]: print(new)
['рука', 'нож', 'аедро', 'Неаполь', 'аиктория', 'материк', 'бровь']
#                                                              ^

For a string:

import re

s = 'Нужно найти в списке слов все слова на букву "в", и заменить букву "в" на букву "а" во всех словах. Как ето сделать, без разбивания каждого слова на буквы и замены по индексу. Большое Спасибо!'
new = re.sub(r'\bв', r'X', s, flags=re.UNICODE)

print(new)

Result:

Нужно найти X списке слов Xсе слова на букву "X", и заменить букву "X" на букву "а" Xо Xсех словах. Как ето сделать, без разбивания каждого слова на б
уквы и замены по индексу. Большое Спасибо!
 4
Author: MaxU, 2017-01-24 13:23:29

To replace the large and small "b" with the small " a " in each word in the list (not just at the beginning of the word):

table = str.maketrans("вВ", "аа")
result = [word.translate(table) for word in a]

Or, without creating a new list:

for i, word in enumerate(a):
    a[i] = word.translate(table)

To replace " in " only at the beginning of a word:

result = ["а" + word[1:] for word in a if word[0] in "вВ"])

Or, without creating a new list:

for i, word in enumerate(a):
    if word[0] in "вВ":
        a[i] = "а" + word[1:]

If the letter you have can take more than one Unicode code point, for example, "e" in NFD form (literal comparison):

if word.startswith(letter):
    a[i] = replacement + word[len(letter):]
 3
Author: jfs, 2017-01-24 19:54:33
replace = lambda s: 'а%s'%s[1:] if s.startswith('в') else s
list(map(replace, a))
 1
Author: vadim vaduxa, 2017-01-25 09:56:38