String methods python replace

Python String replace()

Summary: in this tutorial, you’ll learn how to use the Python string replace() method to replace some or all occurrences of a substring with a new substring.

Introduction to the Python string replace() method

The replace() method returns a copy of a string with some or all matches of a substring replaced with a new substring.

The following shows the syntax of the replace() method:

str.replace(substr, new_substr [, count])Code language: CSS (css)

The replace() method accepts three parameters:

  • substr is a string that is to be replaced by the new_substr .
  • new_substr is the string that replaces the substr
  • count is an integer that specifies the first count number of occurrences of the substr that will be replaced with the new_substr . The count parameter is optional. If you omit the count argument, the replace() method will replace all the occurrences of the substr by the new_substr .

It’s important to note that the replace() method returns a copy of the original string with some or all occurrences of the substr replaced by the new_substr . It doesn’t change the original string.

Читайте также:  Какие кнопочные телефоны поддерживают java

Python string replace() method examples

Let’s take some examples of using the replace() method.

1) Replacing all occurrences of a substring with a new substring

The following example uses the string replace() method to replace all occurrences of the substring ‘We’ by the new substring ‘Python’ :

s = 'We will, We will rock you!' new_s = s.replace('We', 'Python') print(s) print(new_s)Code language: PHP (php)
We will, We will rock you! Python will, Python will rock you!

2) Replacing some occurrences of a substring by a new substring

The following example uses the replace() method to replace the first occurrence of the substring ‘bye’ by the new substring ‘baby’ :

s = 'Baby bye bye bye!' new_s = s.replace('bye', 'baby', 1) print(new_s)Code language: PHP (php)

In this example, we passed the count argument as one. Therefore, the replace() method just replaces the first occurrence of the string ‘bye’ with the string ‘baby’

Summary

  • Use the Python string replace() method to return a copy of a string with some or all occurrences of a substring replaced by a new substring.

Источник

Python String replace() Method

The Python String replace() method replaces all occurrences of one substring in a string with another substring. This method is used to create another string by replacing some parts of the original string, whose gist might remain unmodified.

For example, in real-time applications, this method can be used to replace multiple same spelling mistakes in a document at a time.

This replace() method can also replace selected number of occurrences of substrings in a string instead of replacing them all.

Syntax

Following is the syntax for Python String replace() method −

Parameters

  • old − This is old substring to be replaced.
  • new − This is new substring, which would replace old substring.
  • count − If this optional argument count is given, only the first count occurrences are replaced.

Return Value

This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Example

The following example shows the usage of Python String replace() method.

str = "Welcome to Tutorialspoint" str_replace = str.replace("o", "0") print("String after replacing: " + str_replace)

When we run above program, it produces following result −

String after replacing: Welc0me t0 Tut0rialsp0int

Example

When we pass the substring parameters along with the optional count parameter, the method only replaces the first count occurrences in the string.

In this example below, the input string is created and the method takes three arguments: two substrings and one count value. The return value will be the string obtained after replacing the first count number of occurrences.

str = "Fred fed Ted bread and Ted fed Fred bread." strreplace = str.replace("Ted", "xx", 1) print("String after replacing: " + strreplace)

When we run above program, it produces following result −

String after replacing: Fred fed xx bread and Ted fed Fred bread.

Example

When we pass two substrings and count = 0 as parameters to the method, the original string is returned as the result.

In the following example, we created a string «Learn Python from Tutorialspoint» and tried to replace the word «Python» with «Java» using the replace() method. But, since we have passed the count as 0, this method does not modify the current string, instead of that, it returns the original value («Learn Python from Tutorialspoint»).

str = "Learn Python from Tutorialspoint" strreplace = str.replace("Python", "Java", 0) print("String after replacing: " + strreplace)

If you execute the program above, the outpit is displayed as −

String after replacing: Learn Python from Tutorialspoint

Источник

Python String replace() Method

The replace() method replaces a specified phrase with another specified phrase.

Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

Syntax

Parameter Values

Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences

More Examples

Example

Replace all occurrence of the word «one»:

txt = «one one was a race horse, two two was one too.»

Example

Replace the two first occurrence of the word «one»:

txt = «one one was a race horse, two two was one too.»

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Изучаем метод replace() в Python: простой способ замены подстрок

Изучаем метод replace() в Python: простой способ замены подстрок

Метод replace() в Python используется для замены всех вхождений указанной подстроки в строке на другую подстроку.

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

В этой статье мы рассмотрим, как использовать метод replace() , а также приведем несколько примеров его использования.

Синтаксис

Метод replace() заменяет все вхождения одной подстроки на другую в строке и имеет следующий синтаксис:

  • str — строка, в которой нужно выполнить замену;
  • old — подстрока, которую нужно заменить;
  • new — новая подстрока, которой нужно заменить все вхождения old;
  • count — необязательный параметр, который указывает, сколько раз нужно выполнить замену. По умолчанию заменятся все вхождения old.

Примеры использования метода replace()

Замена символов в строке

Допустим, у вас есть строка, в которой нужно заменить все вхождения одного символа на другой. В этом примере мы заменяем все запятые в строке на точки с помощью метода replace() :

s = '3,14' new_s = s.replace(',', '.') print(new_s) # '3.14'

Замена слов в строке

Метод replace() также может использоваться для замены слов в строке. Например, в следующем примере мы заменяем все вхождения слова «Python» на «JavaScript» в строке:

s = 'Python is my favorite programming language. I love Python!' new_s = s.replace('Python', 'JavaScript') print(new_s) # 'JavaScript is my favorite programming language. I love JavaScript!'

Ограничение количества замен

Метод replace() позволяет ограничить количество замен с помощью параметра count . Например, в следующем примере мы заменяем только первые два вхождения слова «Python» на «JavaScript»:

s = 'Python is my favorite programming language. I love Python!' new_s = s.replace('Python', 'JavaScript', 2) print(new_s) # 'JavaScript is my favorite programming language. I love Python!'

Замена нескольких символов одновременно

Метод replace() также может использоваться для замены нескольких символов одновременно. Например, в следующем примере мы заменяем все вхождения символов a , b и c на символ x :

s = 'abcabc' new_s = s.replace('a', 'x').replace('b', 'x').replace('c', 'x') print(new_s) # 'xxxxxx'

Замена со знаками препинания

Метод replace() может использоваться для замены знаков препинания на пробелы. Например, в следующем примере мы заменяем знаки препинания на пробелы:

s = "Hello, world! This is a test." new_s = s.replace(",", " ").replace("!", " ") print(new_s) # 'Hello world This is a test '

Замена только в начале или в конце строки

Метод replace() заменяет все вхождения подстроки в строке. Если вы хотите заменить только первое вхождение подстроки в строке или только в начале или в конце строки, вам может потребоваться использовать методы startswith() или endswith() . Например, в следующем примере мы заменяем только первое вхождение слова «Python» на «JavaScript»:

s = 'Python is my favorite programming language. I love Python!' new_s = s.replace('Python', 'JavaScript', 1) print(new_s) # 'JavaScript is my favorite programming language. I love Python!'

Использование регулярных выражений

Метод replace() не поддерживает использование регулярных выражений. Если вам нужно использовать регулярные выражения для выполнения замены в строке, вам следует использовать модуль re . Например, мы можем использовать модуль re для замены всех цифр в строке на символ x :

import re s = "123abc456def789" new_s = re.sub(r"\d", "x", s) print(new_s) # 'xxxabcxxxdefxxx'

Заключение

Метод replace() является мощным инструментом для работы со строками в Python. Он позволяет легко заменять все вхождения одной подстроки на другую в строке и может использоваться во многих ситуациях. Также может использоваться для замены нескольких символов одновременно, а также для ограничения количества замен. Однако, при использовании этого метода следует быть осторожным и учитывать специфику конкретной задачи.

Источник

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