Replace python несколько символов

Изменение строки в Python – метод replace

Строки — это важный тип данных, который есть почти в любом языке программирования. Он служит для создания, изменения и сохранения текстовой информации, а также используется при реализации некоторых задач, связанных с числами.

Python даёт программисту много инструментов для работы со строками, в том числе и метод replace() .

Что делает метод

Слово replace имеет дословный перевод «заменять», так что название метода точно описывает его назначение. С помощью replace можно заменить часть строки или её всю на другую строку.

Синтаксис метода выглядит так:

str.replace(old_str, new_str[, count])

В качестве аргументов в метод передаются:

  • old_str – часть исходной строки, которую необходимо заменить.
  • new_str – строка, на которую заменяют исходную строку ( old_str ).
  • count – определяет количество вхождений подстроки, которые необходимо заменить.

Здесь count – не обязательный параметр. Если его не указывать, то будут заменены все вхождения подстрок на новые.

В качестве str используется исходная строка (тип данных string).

Таким образом, метод replace позволяет гибко изменять только необходимые части строки str , работа метода продемонстрирована в следующих примерах:

my_str = "one dog, one cat, one rabbit" #Заменяем все вхождения "one" в строке a = my_str.replace("one", "two") print(a) # Выведет two dog, two cat, two rabbit #Заменяем первое вхождение "one" в строке b = my_str.replace("one", "two", 1) print(b) # Выведет two dog, one cat, one rabbit #Заменяем первые два вхождения "one" в строке c = my_str.replace("one", "two", 2) print(c) # Выведет two dog, two cat, one rabbit

Важно помнить, что строки — это неизменяемые последовательности. Поэтому метод replace не заменяет отдельные символы в целевой строке, вместо этого он создает её копию с нужными изменениями. Это важная особенность языка Python, которую должен знать каждый программист.

Это не очевидно, с помощью метода replace можно заменить сразу несколько значений, например все элементы списка:

str_list = ["кот", "собака", "кот собака", "кот кот"] # в новый список записываем элементы начального списка, измененные # с помощью replace result_list = [elem.replace("кот", "кошка", 1) for elem in str_list] print(result_list) # Выведет ['кошка', 'собака', 'кошка собака', 'кошка кот']

Применение replace для замены нескольких значений

С помощью словаря

Предыдущий пример позволяет заменить несколько элементов, однако все они имеют одно и то же значение «кот». Если необходимо заменить несколько разных значений, например «кот» на «кошка» и «кошка» на «собака», то необходимо реализовать чуть более сложную программу с использованием словарей:

# Функция для замены нескольких значений def multiple_replace(target_str, replace_values): # получаем заменяемое: подставляемое из словаря в цикле for i, j in replace_values.items(): # меняем все target_str на подставляемое target_str = target_str.replace(i, j) return target_str # создаем словарь со значениями и строку, которую будет изменять replace_values = my_str = "У меня есть кот и кошка" # изменяем и печатаем строку my_str = multiple_replace(my_str, replace_values) print(my_str)

Здесь replace используется в функции, аргументы которой исходная строка и словарь со значениями для замены.

Читайте также:  Python requests post header

У этого варианта программы есть один существенный недостаток, программист не может быть уверен в том, какой результат он получит. Дело в том, что словари — это последовательности без определенного порядка, поэтому рассматриваемый пример программы может привести к двум разным результатам в зависимости от того, как интерпретатор расположит элементы словаря:

В Python версии 3.6 и более поздних порядок перебора ключей будет такой же, как и при котором они созданы. В более ранних версиях Python порядок может отличаться.

Для решения этой проблемы можно заменить обычный словарь на упорядоченный словарь OrderedDict , который нужно импортировать следующей командой:

from collections import OrderedDict

Помимо импорта в программе нужно поменять буквально одну строку:

replace_values = OrderedDict([("кот", "кошка"), ("кошка", "собака")])

В этом случае, результат будет «У меня есть собака и собака», если же поменять местами элементы упорядоченного словаря при инициализации следующим образом: OrderedDict([(«кошка», «собака»), («кот», «кошка»)]) , то результат будет «У меня есть кошка и собака».

Вариант со списками

Замену нескольких значений можно реализовать и по-другому, для этого используем списки:

my_str = "У меня есть кот и кошка" # в цикле передаем список (заменяемое, подставляемое) в метод replace for x, y in ("кот", "кошка"), ("кошка", "собака"): my_str = my_str.replace(x, y) print(my_str) # Выведет "У меня есть собака и собака"

В данном примере цикл for делает 2 итерации:

  1. Подставляет в метод replace значения из первого списка: replace(«кот», «кошка»), в результате чего получается строка «У меня есть кошка и кошка».
  2. Подставляет в метод replace значения из второго списка: replace(«кошка», «собака»), получается строка «У меня есть собака и собака».

Другие типы Python и метод replace

Метод replace есть не только у строк, с его помощью программист может изменять последовательности байт, время и дату.

Синтаксис метода для последовательности байт ничем не отличается от синтаксиса для строк, для дат и времени в аргументах метода replace нужно писать идентификатор изменяемой цели, например:

from datetime import date t_date = date(2020, 4, 23) t_date = t_date.replace(day = 11) print(t_date) # Выведет 2020-04-11

Для времени метод replace применяется аналогично.

Источник

Python: Replace multiple characters in a string

In this article, we will discuss different ways to replace multiple characters in a string in Python.

Table of Contents:

sample_string = "This is a sample string"

Now we want the following characters to be replaced in that string,

  • Replace all occurrences of ‘s’ with ‘X’.
  • Replace all occurrences of ‘a’ with ‘Y’.
  • Replace all occurrences of ‘i’ with ‘Z’.
  • Python: Replace multiple characters in a string using for loop

There are different ways to do this. Let’s discuss them one by one,

Frequently Asked:

Python: Replace multiple characters in a string using the replace()

In Python, the String class (Str) provides a method replace(old, new) to replace the sub-strings in a string. It replaces all the occurrences of the old sub-string with the new sub-string.

Читайте также:  Си шарп язык программирования где используется

In Python, there is no concept of a character data type. A character in Python is also a string. So, we can use the replace() method to replace multiple characters in a string.

sample_string = "This is a sample string" char_to_replace = # Iterate over all key-value pairs in dictionary for key, value in char_to_replace.items(): # Replace key character with value character in string sample_string = sample_string.replace(key, value) print(sample_string)

It replaced all the occurrences of,

As strings are immutable in Python and we cannot change its contents. Therefore, replace() function returns a copy of the string with the replaced content.

Python: Replace multiple characters in a string using the translate ()

We can also replace multiple characters in string with other characters using translate() function,

sample_string = "This is a sample string" char_to_replace = # Replace all multiple characters in a string # based on translation table created by dictionary sample_string = sample_string.translate(str.maketrans(char_to_replace)) print(sample_string)

We created that translation table from a dictionary using Str.maketrans() function. We then passed that translation table as an argument to the translate() method of Str, which replaced following characters in string based on that translation table,

  • Character ‘s’ gets replaced with ‘X’.
  • Character ‘a’ gets replaced with ‘Y’.
  • Character ‘i’ gets replaced with ‘Z’.

As strings are immutable in Python and we cannot change its contents. Therefore translate() function returns a copy of the string with the replaced content.

Python: Replace multiple characters in a string using regex

Python provides a regex module (re), and in this module, it provides a function sub() to replace the contents of a string based on patterns. We can use this re.sub() function to substitute/replace multiple characters in a string,

import re sample_string = "This is a sample string" char_to_replace = # Replace multiple characters (s, a and i) in string with values in # dictionary using regex sample_string = re.sub(r"[sai]", lambda x: char_to_replace[x.group(0)], sample_string) print(sample_string)

Here we passed a pattern r’[sai]’ as the first argument, which matches all occurrences of character ‘s’, ‘a’ and ‘i’. As the second argument in the sub() function, we passed a lambda function, which fetches the matched character from the match object and then returns the value associated with it from the dictionary. Then as the third argument, we passed the original string.

Now for each character in the string that matches the pattern, it calls the lambda function, which gives the replacement character. Then the sub() function replaces that character in the string.

It replaced all the occurrences of,

As strings are immutable in Python and we cannot change its contents. Therefore sub() function of the regex module returns a copy of the string with the replaced content.

Python: Replace multiple characters in a string using for loop

Initialize a new empty string and then iterate over all characters of the original string. During iteration, for each check, if the character exists in the dictionary char_to_replaced or not,

  • If yes, the fetch replacement of that character and add to the new string.
  • If no, then add the character to the new string.
sample_string = "This is a sample string" char_to_replace = result = '' # Iterate over all characters in string for elem in sample_string: # Check if character is in dict as key if elem in char_to_replace: # If yes then add the value of that char # from dict to the new string result += char_to_replace[elem] else: # If not then add the character in new string result += elem print(result)

It replaced all the occurrences of,

Читайте также:  Xml css font color

As strings are immutable in Python and we cannot change its contents. Therefore, we created a new copy of the string with the replaced content.

We can replace multiple characters in a string using replace() , regex.sub(), translate() or for loop in python.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Оцените статью