Home >Backend Development >Python Tutorial >How Do I Replace Substrings in Python 3.x?

How Do I Replace Substrings in Python 3.x?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 13:17:01469browse

How Do I Replace Substrings in Python 3.x?

How to Replace Substrings in Python 3.x

Introduction:

Python's string.replace() method was deprecated in Python 3.x. This article explores the new and recommended approach for replacing substrings in Python 3.

New Method: Using str.replace()

As in Python 2.x, Python 3.x provides the str.replace() method as the replacement for string.replace(). It follows the same syntax and behavior:

original_string.replace(old_substring, new_substring, count)
  • original_string: The string to perform the replacement on.
  • old_substring: The substring to be replaced.
  • new_substring: The substring to replace with.
  • count (optional): An integer specifying the maximum number of occurrences of old_substring to replace (default is unlimited).

Example:

To replace the word "world" with "Guido" in the string "Hello world":

>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'

Additional Notes:

  • str.replace() returns a new string with the replacements applied, while the original string remains unchanged.
  • If old_substring is not found in the string, the original string is returned.
  • Specifying count ensures that only a certain number of occurrences of the substring are replaced. For example, replace the first two occurrences of "is" with "are":
>>> 'This is is is not is a test'.replace('is', 'are', 2)
'This are are is not is a test'

The above is the detailed content of How Do I Replace Substrings in Python 3.x?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn