It is necessary to find in the list of words all the words with the letter "в" , and replace the letter "в" with the letter "а" in all the words. How to do it, without breaking each word into letters and replacing by index. Example:

Entrance:

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

Output:

 a=['рука', 'нож', 'аедро', 'Неаполь', 'аиктория', 'материк'] 
  • Give an example of the input data and what you want to get at the output ... - MaxU
  • @ MaxU, Entry: a = [hand, knife, bucket, Naples, Victoria, mainland] Exit: a = [hand, knife, aedro, Naples, direction, mainland] - Awesome Man

3 answers 3

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 the string:

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

Result:

 Нужно найти X списке слов Xсе слова на букву "X", и заменить букву "X" на букву "а" Xо Xсех словах. Как ето сделать, без разбивания каждого слова на б уквы и замены по индексу. Большое Спасибо! 
  • which means "142" here: "In [142]: Out [142]:"? - Awesome Man
  • 3
    This iPython (interactive Python) marks and numbers input and output. By the way, I highly recommend iPython (the console version) or Jupyter (GUI in the browser) for working with Python ... - MaxU

To replace the large and small "in" with a small "a" in each word in the list (not only 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 the "in" only at the beginning of the 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 you can have a letter with more than one Unicode code point, for example, “e” in the NFD form (literal comparison):

 if word.startswith(letter): a[i] = replacement + word[len(letter):] 
     replace = lambda s: 'а%s'%s[1:] if s.startswith('в') else s list(map(replace, a))