Как заменить символ в строке Python

Замена символов в строках является одной из распространенных операций при работе с текстовыми данными в Python. Эта операция может быть полезна во множестве сценариев, таких как удаление, замена определенных символов, обработка специальных символов, а также валидация и преобразование текстовых данных.
В этом разделе мы рассмотрим различные методы замены символов в строке в Python. Мы ознакомимся с основными методами, такими как replace() , translate() и join() , которые предоставляют удобные инструменты для выполнения замены символов в строке. Также мы рассмотрим использование регулярных выражений с помощью модуля re , который предоставляет более мощные и гибкие возможности для замены символов на основе шаблонов, и замену символа по его индексу с помощью срезов.
Замена символа в строке Python с помощью метода replace()
Метод replace() является одним из наиболее простых и популярных способов замены символов в строке в Python. Он позволяет заменить все вхождения указанного символа или подстроки в строке на другую строку.
Синтаксис метода replace() выглядит следующим образом:
- string : это исходная строка, в которой нужно выполнить замену символа или подстроки.
- old : это символ или подстрока, которые нужно заменить.
- new : это строка, на которую нужно заменить найденные символы или подстроки.
- count (необязательный аргумент): это максимальное количество замен, которые нужно выполнить. Если он не указан, то все вхождения будут заменены.
Пример использования метода replace() для замены символа в строке:
В данном примере мы использовали метод replace() для замены символа «,» на символ «!». Результат замены сохранен в новую переменную new_text , и после выполнения программы мы получили измененную строку «Hello! world!».
Обратите внимание, что метод replace() создает новую строку с замененными символами, и исходная строка остается неизменной. Если нужно изменить исходную строку, необходимо присвоить ее новое значение с помощью оператора присваивания ( = ), как показано в примере выше.
Метод replace() также поддерживает более сложные операции замены, такие как замена нескольких символов или подстрок, использование регулярных выражений и т. д.
Замена символа в строке Python с помощью метода translate()
Метод translate() представляет более мощный и гибкий способ замены символов в строке в Python. Он позволяет выполнять замены с использованием таблицы перевода символов, что делает его особенно полезным для замены нескольких символов или выполнения сложных операций замены с использованием различных правил.
Синтаксис метода translate() выглядит следующим образом:
- string : это исходная строка, в которой нужно выполнить замену символов.
- table : это таблица перевода символов, представляющая собой словарь или объект типа str.maketrans , созданный с помощью метода str.maketrans() .
- deletechars (необязательный аргумент): это строка, содержащая символы, которые нужно удалить из исходной строки.
Пример использования метода translate() для замены символа в строке:
данном примере мы создали таблицу перевода символов с помощью метода str.maketrans() , указав символ «,» как символ для замены и символ «!» как символ замены. Затем мы использовали метод translate() для выполнения замены в исходной строке. Результат замены сохранен в новую переменную new_text , и после выполнения программы мы получили измененную строку «Hello! world!».
Метод translate() также позволяет удалять символы из строки, указав их в аргументе deletechars , и выполнять более сложные операции замены, такие как замена подстрок, использование регулярных выражений и т. д.
Замена символа в строке Python с помощью метода join()
Метод join() в Python используется для объединения элементов списка или другого итерируемого объекта в строку, разделяя их указанным разделителем. Однако, этот метод также может быть использован для замены символов в строке путем присоединения новых символов к существующей строке.
Синтаксис метода join() выглядит следующим образом:
- разделитель : это строка, которая будет использована в качестве разделителя между элементами списка или другого итерируемого объекта.
- список_или_другой_итерируемый_объект : это список или другой итерируемый объект, элементы которого нужно объединить в строку.
Пример использования метода join() для замены символа в строке:
В данном примере мы использовали метод split() для разделения исходной строки text по символу «,» и создания списка, содержащего элементы строки между разделителями. Затем мы использовали метод join() с разделителем «!» для объединения элементов списка в новую строку. Результат замены сохранен в переменной new_text , и после выполнения программы мы получили измененную строку «Hello! world!».
Метод join() также может быть использован для замены более сложных подстрок в строке путем создания списка, содержащего новые значения, и их объединения с использованием разделителя. Этот метод является эффективным способом замены символов в строке, особенно при работе с большими текстовыми данными.
Замена символа в строке Python с помощью регулярных выражений
Регулярные выражения (Regular Expressions) — мощный инструмент для работы с текстовыми данными, включая замену символов в строке. В Python регулярные выражения реализованы в модуле re , который предоставляет функциональность для работы с регулярными выражениями.
Для замены символа или подстроки в строке с использованием регулярных выражений в Python, можно воспользоваться функцией re.sub() из модуля re . Синтаксис функции re.sub() выглядит следующим образом:
- шаблон : это регулярное выражение, которое указывает, какие символы или подстроки нужно найти в строке для замены.
- замена : это строка, на которую будут заменены найденные символы или подстроки.
- строка : это исходная строка, в которой производится замена.
Пример использования функции re.sub() для замены символа в строке:
В данном примере мы использовали регулярное выражение r»,» , которое указывает на символ «,». Затем мы передали это выражение в функцию re.sub() в качестве шаблона для поиска символа «,» в исходной строке text , и указали строку «!» в качестве замены. Результат замены сохранен в переменной new_text , и после выполнения программы мы получили измененную строку «Hello! world!».
Функция re.sub() также поддерживает более сложные регулярные выражения, что позволяет осуществлять более гибкую замену символов или подстрок в строке. Однако, при использовании регулярных выражений необходимо быть внимательными, так как неправильно составленное выражение может привести к нежелательным результатам.
Замена символа в строке Python по его индексу
Еще один способ замены символа в строке Python — это использование индексации строк и операции присваивания. В Python строки являются неизменяемыми (immutable) объектами, поэтому нельзя просто так заменить символ в строке. Однако, можно создать новую строку, скопировав часть исходной строки с заменой нужного символа.
Пример замены символа в строке по его индексу:
В данном примере мы использовали операцию среза ( text[:7] и text[8:] ), чтобы скопировать части исходной строки до и после заменяемого символа на позиции 7 (индексация в Python начинается с 0). Затем мы конкатенировали эти части с новым символом «W» с помощью оператора + и сохранили результат в переменной new_text . В итоге, мы получили измененную строку «Hello, World!».
Однако, стоит отметить, что при замене символа в строке по его индексу нужно быть осторожными с выходом за пределы длины строки, чтобы избежать ошибок индексации. Также, при замене символа в строке с использованием операции присваивания, создается новая строка, что может быть неэффективным при работе с большими строками. В таких случаях, более эффективными могут быть другие методы замены символов, такие как использование методов replace() , translate() или регулярных выражений, которые описаны в предыдущих разделах.
Изучаем метод replace() в Python: простой способ замены подстрок
Метод replace() в Python используется для замены всех вхождений указанной подстроки в строке на другую подстроку.
Его можно использовать для многих задач, таких как изменение текстовых файлов, удаление или замена определенных символов или строк в строке.
В этой статье мы рассмотрим, как использовать метод replace() , а также приведем несколько примеров его использования.
Синтаксис
Метод replace() заменяет все вхождения одной подстроки на другую в строке и имеет следующий синтаксис:
- str — строка, в которой нужно выполнить замену;
- old — подстрока, которую нужно заменить;
- new — новая подстрока, которой нужно заменить все вхождения old;
- count — необязательный параметр, который указывает, сколько раз нужно выполнить замену. По умолчанию заменятся все вхождения old.
Примеры использования метода replace()
Замена символов в строке
Допустим, у вас есть строка, в которой нужно заменить все вхождения одного символа на другой. В этом примере мы заменяем все запятые в строке на точки с помощью метода replace() :
Замена слов в строке
Метод replace() также может использоваться для замены слов в строке. Например, в следующем примере мы заменяем все вхождения слова «Python» на «JavaScript» в строке:
Ограничение количества замен
Метод replace() позволяет ограничить количество замен с помощью параметра count . Например, в следующем примере мы заменяем только первые два вхождения слова «Python» на «JavaScript»:
Замена нескольких символов одновременно
Метод replace() также может использоваться для замены нескольких символов одновременно. Например, в следующем примере мы заменяем все вхождения символов a , b и c на символ x :
Замена со знаками препинания
Метод replace() может использоваться для замены знаков препинания на пробелы. Например, в следующем примере мы заменяем знаки препинания на пробелы:
Замена только в начале или в конце строки
Метод replace() заменяет все вхождения подстроки в строке. Если вы хотите заменить только первое вхождение подстроки в строке или только в начале или в конце строки, вам может потребоваться использовать методы startswith() или endswith() . Например, в следующем примере мы заменяем только первое вхождение слова «Python» на «JavaScript»:
Использование регулярных выражений
Метод replace() не поддерживает использование регулярных выражений. Если вам нужно использовать регулярные выражения для выполнения замены в строке, вам следует использовать модуль re . Например, мы можем использовать модуль re для замены всех цифр в строке на символ x :
Заключение
Метод replace() является мощным инструментом для работы со строками в Python. Он позволяет легко заменять все вхождения одной подстроки на другую в строке и может использоваться во многих ситуациях. Также может использоваться для замены нескольких символов одновременно, а также для ограничения количества замен. Однако, при использовании этого метода следует быть осторожным и учитывать специфику конкретной задачи.
How to Replace a String in Python
If you’re looking for ways to remove or replace all or part of a string in Python, then this tutorial is for you. You’ll be taking a fictional chat room transcript and sanitizing it using both the .replace() method and the re.sub() function.
In Python, the .replace() method and the re.sub() function are often used to clean up text by removing strings or substrings or replacing them. In this tutorial, you’ll be playing the role of a developer for a company that provides technical support through a one-to-one text chat. You’re tasked with creating a script that’ll sanitize the chat, removing any personal data and replacing any swear words with emoji.
You’re only given one very short chat transcript:
Even though this transcript is short, it’s typical of the type of chats that agents have all the time. It has user identifiers, ISO time stamps, and messages.
In this case, the client johndoe filed a complaint, and company policy is to sanitize and simplify the transcript, then pass it on for independent evaluation. Sanitizing the message is your job!
Sample Code: Click here to download the free sample code that you’ll use to replace strings in Python.
The first thing you’ll want to do is to take care of any swear words.
How to Remove or Replace a Python String or Substring
The most basic way to replace a string in Python is to use the .replace() string method:
As you can see, you can chain .replace() onto any string and provide the method with two arguments. The first is the string that you want to replace, and the second is the replacement.
Note: Although the Python shell displays the result of .replace() , the string itself stays unchanged. You can see this more clearly by assigning your string to a variable:
Notice that when you simply call .replace() , the value of name doesn’t change. But when you assign the result of name.replace() to the name variable, ‘Fake Python’ becomes ‘Real Python’ .
Now it’s time to apply this knowledge to the transcript:
Loading the transcript as a triple-quoted string and then using the .replace() method on one of the swear words works fine. But there’s another swear word that’s not getting replaced because in Python, the string needs to match exactly:
As you can see, even if the casing of one letter doesn’t match, it’ll prevent any replacements. This means that if you’re using the .replace() method, you’ll need to call it various times with the variations. In this case, you can just chain on another call to .replace() :
Success! But you’re probably thinking that this isn’t the best way to do this for something like a general-purpose transcription sanitizer. You’ll want to move toward some way of having a list of replacements, instead of having to type out .replace() each time.
Set Up Multiple Replacement Rules
There are a few more replacements that you need to make to the transcript to get it into a format acceptable for independent review:
- Shorten or remove the time stamps
- Replace the usernames with Agent and Client
Now that you’re starting to have more strings to replace, chaining on .replace() is going to get repetitive. One idea could be to keep a list of tuples, with two items in each tuple. The two items would correspond to the arguments that you need to pass into the .replace() method—the string to replace and the replacement string:
In this version of your transcript-cleaning script, you created a list of replacement tuples, which gives you a quick way to add replacements. You could even create this list of tuples from an external CSV file if you had loads of replacements.
You then iterate over the list of replacement tuples. In each iteration, you call .replace() on the string, populating the arguments with the old and new variables that have been unpacked from each replacement tuple.
Note: The unpacking in the for loop in this case is functionally the same as using indexing:
If you’re mystified by unpacking, then check out the section on unpacking from the tutorial on Python lists and tuples.
With this, you’ve made a big improvement in the overall readability of the transcript. It’s also easier to add replacements if you need to. Running this script reveals a much cleaner transcript:
That’s a pretty clean transcript. Maybe that’s all you need. But if your inner automator isn’t happy, maybe it’s because there are still some things that may be bugging you:
- Replacing the swear words won’t work if there’s another variation using -ing or a different capitalization, like BLAst.
- Removing the date from the time stamp currently only works for August 24, 2022.
- Removing the full time stamp would involve setting up replacement pairs for every possible time—not something you’re too keen on doing.
- Adding the space after Agent in order to line up your columns works but isn’t very general.
If these are your concerns, then you may want to turn your attention to regular expressions.
Leverage re.sub() to Make Complex Rules
Whenever you’re looking to do any replacing that’s slightly more complex or needs some wildcards, you’ll usually want to turn your attention toward regular expressions, also known as regex.
Regex is a sort of mini-language made up of characters that define a pattern. These patterns, or regexes, are typically used to search for strings in find and find and replace operations. Many programming languages support regex, and it’s widely used. Regex will even give you superpowers.
In Python, leveraging regex means using the re module’s sub() function and building your own regex patterns:
While you can mix and match the sub() function with the .replace() method, this example only uses sub() , so you can see how it’s used. You’ll note that you can replace all variations of the swear word by using just one replacement tuple now. Similarly, you’re only using one regex for the full time stamp:
Now your transcript has been completely sanitized, with all noise removed! How did that happen? That’s the magic of regex.
The first regex pattern, «blast\w*» , makes use of the \w special character, which will match alphanumeric characters and underscores. Adding the * quantifier directly after it will match zero or more characters of \w .
Another vital part of the first pattern is that the re.IGNORECASE flag makes it a case-insensitive pattern. So now, any substring containing blast , regardless of capitalization, will be matched and replaced.
Note: The «blast\w*» pattern is quite broad and will also modify fibroblast to fibro . It also can’t identify a polite use of the word. It just matches the characters. That said, the typical swear words that you’d want to censor don’t really have polite alternate meanings!
The second regex pattern uses character sets and quantifiers to replace the time stamp. You often use character sets and quantifiers together. A regex pattern of [abc] , for example, will match one character of a , b , or c . Putting a * directly after it would match zero or more characters of a , b , or c .
There are more quantifiers, though. If you used [abc] <10>, it would match exactly ten characters of a , b or c in any order and any combination. Also note that repeating characters is redundant, so [aa] is equivalent to [a] .
For the time stamp, you use an extended character set of [-T:+\d] to match all the possible characters that you might find in the time stamp. Paired with the quantifier <25>, this will match any possible time stamp, at least until the year 10,000.
Note: The special character, \d , matches any digit character.
The time stamp regex pattern allows you to select any possible date in the time stamp format. Seeing as the the times aren’t important for the independent reviewer of these transcripts, you replace them with an empty string. It’s possible to write a more advanced regex that preserves the time information while removing the date.
The third regex pattern is used to select any user string that starts with the keyword «support» . Note that you escape ( \ ) the square bracket ( [ ) because otherwise the keyword would be interpreted as a character set.
Finally, the last regex pattern selects the client username string and replaces it with «Client» .
Note: While it would be great fun to go into more detail about these regex patterns, this tutorial isn’t about regex. Work through the Python regex tutorial for a good primer on the subject. Also, you can make use of the fantastic RegExr web site, because regex is tricky and regex wizards of all levels rely on handy tools like RegExr.
RegExr is particularly good because you can copy and paste regex patterns, and it’ll break them down for you with explanations.
With regex, you can drastically cut down the number of replacements that you have to write out. That said, you still may have to come up with many patterns. Seeing as regex isn’t the most readable of languages, having lots of patterns can quickly become hard to maintain.
Thankfully, there’s a neat trick with re.sub() that allows you to have a bit more control over how replacement works, and it offers a much more maintainable architecture.
Use a Callback With re.sub() for Even More Control
One trick that Python and sub() have up their sleeves is that you can pass in a callback function instead of the replacement string. This gives you total control over how to match and replace.
To get started building this version of the transcript-sanitizing script, you’ll use a basic regex pattern to see how using a callback with sub() works:
The regex pattern that you’re using will match the time stamps, and instead of providing a replacement string, you’re passing in a reference to the sanitize_message() function. Now, when sub() finds a match, it’ll call sanitize_message() with a match object as an argument.
Since sanitize_message() just prints the object that it’s received as an argument, when running this, you’ll see the match objects being printed to the console:
A match object is one of the building blocks of the re module. The more basic re.match() function returns a match object. sub() doesn’t return any match objects but uses them behind the scenes.
Because you get this match object in the callback, you can use any of the information contained within it to build the replacement string. Once it’s built, you return the new string, and sub() will replace the match with the returned string.
Apply the Callback to the Script
In your transcript-sanitizing script, you’ll make use of the .groups() method of the match object to return the contents of the two capture groups, and then you can sanitize each part in its own function or discard it:
Instead of having lots of different regexes, you can have one top level regex that can match the whole line, dividing it up into capture groups with brackets ( () ). The capture groups have no effect on the actual matching process, but they do affect the match object that results from the match:
- \[(.+)\] matches any sequence of characters wrapped in square brackets. The capture group picks out the username string, for instance johndoe .
- [-T:+\d] <25>matches the time stamp, which you explored in the last section. Since you won’t be using the time stamp in the final transcript, it’s not captured with brackets.
- : matches a literal colon. The colon is used as a separator between the message metadata and the message itself.
- (.+) matches any sequence of characters until the end of the line, which will be the message.
The content of the capturing groups will be available as separate items in the match object by calling the .groups() method, which returns a tuple of the matched strings.
Note: The entry regex definition uses Python’s implicit string concatenation:
Functionally, this is the same as writing it all out as one single string: r»\[(.+)\] [-T:+\d] <25>: (.+)» . Organizing your longer regex patterns on separate lines allow you to break it up into chunks, which not only makes it more readable but also allow you to insert comments too.
The two groups are the user string and the message. The .groups() method returns them as a tuple of strings. In the sanitize_message() function, you first use unpacking to assign the two strings to variables:
Note how this architecture allows a very broad and inclusive regex at the top level, and then lets you supplement it with more precise regexes within the replacement callback.
The sanitize_message() function makes use of two functions to clean up usernames and bad words. It additionally uses f-strings to justify the messages. Note how censor_bad_words() uses a dynamically created regex while censor_users() relies on more basic string processing.
This is now looking like a good first prototype for a transcript-sanitizing script! The output is squeaky clean:
Nice! Using sub() with a callback gives you far more flexibility to mix and match different methods and build regexes dynamically. This structure also gives you the most room to grow when your bosses or clients inevitably change their requirements on you!
Conclusion
In this tutorial, you’ve learned how to replace strings in Python. Along the way, you’ve gone from using the basic Python .replace() string method to using callbacks with re.sub() for absolute control. You’ve also explored some regex patterns and deconstructed them into a better architecture to manage a replacement script.
With all that knowledge, you’ve successfully cleaned a chat transcript, which is now ready for independent review. Not only that, but your transcript-sanitizing script has plenty of room to grow.
Sample Code: Click here to download the free sample code that you’ll use to replace strings in Python.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Replacing a String in Python
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About Ian Currie
Ian is a Python nerd who uses it for everything from tinkering to helping people and companies manage their day-to-day and develop their businesses.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:




Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
Метод str.replace() в Python, меняет подстроку/символ в строке
Производит поиск и замену подстроки (символа) в строке
Синтаксис:
Параметры:
- old — str , подстрока или символ который меняем
- new — str , подстрока или символ на который меняем
- count — int , сколько раз меняем
Возвращаемое значение:
- измененная копия строки.
Описание:
Метод str.replace() вернет копию строки, в которой все вхождения подстроки old заменены на подстроку new .
Если указан необязательный аргумент count , заменяются только первые вхождения count .
Примечание. Производить поиск и замену подстроки/символа в строке можно так же при помощи регулярных выражений, используя функцию re.sub() .
Общие примеры замены подстроки/символа в строке.
Замены нескольких значений в строке одной операцией.
Для замены нескольких разных символов/подстрок в одной операции (множественная замена) необходимо определить функцию, которая будет принимать исходную строку и список символов/подстрок, каждая со своим новым значением. Символы/подстроки с новыми значениями можно передавать разными способами, например как список двойных кортежей в виде [('old', 'new'), . ] или как словарь, где ключ будет старым значением, а значение — новым <'old': 'new', . >. В зависимости от того, в каком виде передаются значения, будет строится логика извлечения этих значений для осуществления замены в исходной строке.
В примере будем передавать символы/подстроки с их новыми значениями в виде кортежа, так как он дает больше гибкости. Гибкость будет состоять в том, что в примере будет возможность добавления количества замены каждого символа/подстроки в строке.
Из примера видим, что новая функция replace() работает как и ожидается, а именно символ 'а' заменился 3 раза, символ 'б' и подстрока 'кад' заменились по количеству совпадений.