Как заменить слово в строке python
Перейти к содержимому

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

  • автор:

A Guide on Python String replace() Method

Ezzeddin Abdullah

Replacing characters in strings using Python can be done with multiple ways. In this quick tutorial, you'll learn how to use the replace method to manipulate strings.

You'll learn through examples how to replace a character in a string, how to replace multiple characters in a string, and how to replace the last character in a string.

# String Methods

Python’s string type provides many functions that act on the capitalization of a string. These include :

  • str.casefold
  • str.upper
  • str.lower
  • str.capitalize
  • str.title
  • str.swapcase

With unicode strings (the default in Python 3), these operations are not 1:1 mappings or reversible. Most of these operations are intended for display purposes, rather than normalization.

# str.casefold()

str.casefold creates a lowercase string that is suitable for case insensitive comparisons. This is more aggressive than str.lower and may modify strings that are already in lowercase or cause strings to grow in length, and is not intended for display purposes.

The transformations that take place under casefolding are defined by the Unicode Consortium in the CaseFolding.txt file on their website.

# str.upper()

str.upper takes every character in a string and converts it to its uppercase equivalent, for example:

# str.lower()

str.lower does the opposite; it takes every character in a string and converts it to its lowercase equivalent:

# str.capitalize()

str.capitalize returns a capitalized version of the string, that is, it makes the first character have upper case and the rest lower:

# str.title()

str.title returns the title cased version of the string, that is, every letter in the beginning of a word is made upper case and all others are made lower case:

# str.swapcase()

str.swapcase returns a new string object in which all lower case characters are swapped to upper case and all upper case characters to lower:

# Usage as str class methods

It is worth noting that these methods may be called either on string objects (as shown above) or as a class method of the str class (with an explicit call to str.upper , etc.)

This is most useful when applying one of these methods to many strings at once in say, a map

# str.translate: Translating characters in a string

Python supports a translate method on the str type which allows you to specify the translation table (used for replacements) as well as any characters which should be deleted in the process.

The translate method returns a string which is a translated copy of the original string.

You can set the table argument to None if you only need to delete characters.

# str.format and f-strings: Format values into a string

Python provides string interpolation and formatting functionality through the str.format function, introduced in version 2.6 and f-strings introduced in version 3.6.

Given the following variables:

The following statements are all equivalent

For reference, Python also supports C-style qualifiers for string formatting. The examples below are equivalent to those above, but the str.format versions are preferred due to benefits in flexibility, consistency of notation, and extensibility:

The braces uses for interpolation in str.format can also be numbered to reduce duplication when formatting strings. For example, the following are equivalent:

While the official python documentation is, as usual, thorough enough, pyformat.info

(opens new window) has a great set of examples with detailed explanations.

Additionally, the < and >characters can be escaped by using double brackets:

(opens new window) for additional information. str.format() was proposed in PEP 3101

# String module’s useful constants

Python’s string module provides constants for string related operations. To use them, import the string module:

# string.ascii_letters :

Concatenation of ascii_lowercase and ascii_uppercase :

# string.ascii_lowercase :

Contains all lower case ASCII characters:

# string.ascii_uppercase :

Contains all upper case ASCII characters:

# string.digits :

Contains all decimal digit characters:

# string.hexdigits :

Contains all hex digit characters:

# string.octaldigits :

Contains all octal digit characters:

# string.punctuation :

Contains all characters which are considered punctuation in the C locale:

# string.whitespace :

Contains all ASCII characters considered whitespace:

In script mode, print(string.whitespace) will print the actual characters, use str to get the string returned above.

# string.printable :

Contains all characters which are considered printable; a combination of string.digits , string.ascii_letters , string.punctuation , and string.whitespace .

# Split a string based on a delimiter into a list of strings

# str.split(sep=None, maxsplit=-1)

str.split takes a string and returns a list of substrings of the original string. The behavior differs depending on whether the sep argument is provided or omitted.

If sep isn’t provided, or is None , then the splitting takes place wherever there is whitespace. However, leading and trailing whitespace is ignored, and multiple consecutive whitespace characters are treated the same as a single whitespace character:

The sep parameter can be used to define a delimiter string. The original string is split where the delimiter string occurs, and the delimiter itself is discarded. Multiple consecutive delimiters are not treated the same as a single occurrence, but rather cause empty strings to be created.

The default is to split on every occurrence of the delimiter, however the maxsplit parameter limits the number of splittings that occur. The default value of -1 means no limit:

# str.rsplit(sep=None, maxsplit=-1)

str.rsplit ("right split") differs from str.split ("left split") when maxsplit is specified. The splitting starts at the end of the string rather than at the beginning:

Note: Python specifies the maximum number of splits performed, while most other programming languages specify the maximum number of substrings created. This may create confusion when porting or comparing code.

# Replace all occurrences of one substring with another substring

Python’s str type also has a method for replacing occurences of one sub-string with another sub-string in a given string. For more demanding cases, one can use re.sub

# str.replace(old, new[, count]) :

str.replace takes two arguments old and new containing the old sub-string which is to be replaced by the new sub-string. The optional argument count specifies the number of replacements to be made:

For example, in order to replace ‘foo’ with ‘spam’ in the following string, we can call str.replace with old = ‘foo’ and new = ‘spam’ :

If the given string contains multiple examples that match the old argument, all occurrences are replaced with the value supplied in new :

unless, of course, we supply a value for count . In this case count occurrences are going to get replaced:

# Testing what a string is composed of

Python’s str type also features a number of methods that can be used to evaluate the contents of a string. These are str.isalpha , str.isdigit , str.isalnum , str.isspace . Capitalization can be tested with str.isupper , str.islower and str.istitle .

# str.isalpha

str.isalpha takes no arguments and returns True if the all characters in a given string are alphabetic, for example:

As an edge case, the empty string evaluates to False when used with "".isalpha() .

# str.isupper , str.islower , str.istitle

These methods test the capitalization in a given string.

str.isupper is a method that returns True if all characters in a given string are uppercase and False otherwise.

Conversely, str.islower is a method that returns True if all characters in a given string are lowercase and False otherwise.

str.istitle returns True if the given string is title cased; that is, every word begins with an uppercase character followed by lowercase characters.

# str.isdecimal , str.isdigit , str.isnumeric

str.isdecimal returns whether the string is a sequence of decimal digits, suitable for representing a decimal number.

str.isdigit includes digits not in a form suitable for representing a decimal number, such as superscript digits.

str.isnumeric includes any number values, even if not digits, such as values outside the range 0-9.

Bytestrings ( bytes in Python 3, str in Python 2), only support isdigit , which only checks for basic ASCII digits.

As with str.isalpha , the empty string evaluates to False .

# str.isalnum

This is a combination of str.isalpha and str.isnumeric , specifically it evaluates to True if all characters in the given string are alphanumeric, that is, they consist of alphabetic or numeric characters:

# str.isspace

Evaluates to True if the string contains only whitespace characters.

Sometimes a string looks “empty” but we don’t know whether it’s because it contains just whitespace or no character at all

To cover this case we need an additional test

But the shortest way to test if a string is empty or just contains whitespace characters is to use strip

(opens new window) (with no arguments it removes all leading and trailing whitespace characters)

# Stripping unwanted leading/trailing characters from a string

Three methods are provided that offer the ability to strip leading and trailing characters from a string: str.strip , str.rstrip and str.lstrip . All three methods have the same signature and all three return a new string object with unwanted characters removed.

# str.strip([chars])

str.strip acts on a given string and removes (strips) any leading or trailing characters contained in the argument chars ; if chars is not supplied or is None , all white space characters are removed by default. For example:

If chars is supplied, all characters contained in it are removed from the string, which is returned. For example:

# str.rstrip([chars]) and str.lstrip([chars])

These methods have similar semantics and arguments with str.strip() , their difference lies in the direction from which they start. str.rstrip() starts from the end of the string while str.lstrip() splits from the start of the string.

For example, using str.rstrip :

While, using str.lstrip :

# Reversing a string

A string can reversed using the built-in reversed() function, which takes a string and returns an iterator in reverse order.

reversed() can be wrapped in a call to ».join() to make a string

While using reversed() might be more readable to uninitiated Python users, using extended slicing

(opens new window) with a step of -1 is faster and more concise. Here , try to implement it as function:

# Join a list of strings into one string

A string can be used as a separator to join a list of strings together into a single string using the join() method. For example you can create a string where each element in a list is separated by a space.

The following example separates the string elements with three hyphens.

# String Contains

Python makes it extremely intuitive to check if a string contains a given substring. Just use the in operator:

Note: testing an empty string will always result in True :

# Counting number of times a substring appears in a string

One method is available for counting the number of occurrences of a sub-string in another string, str.count .

# str.count(sub[, start[, end]])

str.count returns an int indicating the number of non-overlapping occurrences of the sub-string sub in another string. The optional arguments start and end indicate the beginning and the end in which the search will take place. By default start = 0 and end = len(str) meaning the whole string will be searched:

By specifying a different value for start , end we can get a more localized search and count, for example, if start is equal to 13 the call to:

is equivalent to:

# Case insensitive string comparisons

Comparing string in a case insensitive way seems like something that’s trivial, but it’s not. This section only considers unicode strings (the default in Python 3). Note that Python 2 may have subtle weaknesses relative to Python 3 — the later’s unicode handling is much more complete.

The first thing to note it that case-removing conversions in unicode aren’t trivial. There is text for which text.lower() != text.upper().lower() , such as "ß" :

But let’s say you wanted to caselessly compare "BUSSE" and "Buße" . Heck, you probably also want to compare "BUSSE" and "BUẞE" equal — that’s the newer capital form. The recommended way is to use casefold :

Do not just use lower . If casefold is not available, doing .upper().lower() helps (but only somewhat).

Then you should consider accents. If your font renderer is good, you probably think "ê" == "ê" — but it doesn’t:

This is because they are actually

The simplest way to deal with this is unicodedata.normalize . You probably want to use NFKD normalization, but feel free to check the documentation. Then one does

To finish up, here this is expressed in functions:

# Test the starting and ending characters of a string

In order to test the beginning and ending of a given string in Python, one can use the methods str.startswith() and str.endswith() .

# str.startswith(prefix[, start[, end]])

As it’s name implies, str.startswith is used to test whether a given string starts with the given characters in prefix .

The optional arguments start and end specify the start and end points from which the testing will start and finish. In the following example, by specifying a start value of 2 our string will be searched from position 2 and afterwards:

This yields True since s[2] == ‘i’ and s[3] == ‘s’ .

You can also use a tuple to check if it starts with any of a set of strings

# str.endswith(prefix[, start[, end]])

str.endswith is exactly similar to str.startswith with the only difference being that it searches for ending characters and not starting characters. For example, to test if a string ends in a full stop, one could write:

as with startswith more than one characters can used as the ending sequence:

You can also use a tuple to check if it ends with any of a set of strings

# Justify strings

Python provides functions for justifying strings, enabling text padding to make aligning various strings much easier.

Below is an example of str.ljust and str.rjust :

ljust and rjust are very similar. Both have a width parameter and an optional fillchar parameter. Any string created by these functions is at least as long as the width parameter that was passed into the function. If the string is longer than width alread, it is not truncated. The fillchar argument, which defaults to the space character ‘ ‘ must be a single character, not a multicharacter string.

The ljust function pads the end of the string it is called on with the fillchar until it is width characters long. The rjust function pads the beginning of the string in a similar fashion. Therefore, the l and r in the names of these functions refer to the side that the original string, not the fillchar , is positioned in the output string.

# Conversion between str or bytes data and unicode characters

The contents of files and network messages may represent encoded characters. They often need to be converted to unicode for proper display.

In Python 2, you may need to convert str data to Unicode characters. The default ( » , "" , etc.) is an ASCII string, with any values outside of ASCII range displayed as escaped values. Unicode strings are u» (or u"" , etc.).

In Python 3 you may need to convert arrays of bytes (referred to as a ‘byte literal’) to strings of Unicode characters. The default is now a Unicode string, and bytestring literals must now be entered as b» , b"" , etc. A byte literal will return True to isinstance(some_val, byte) , assuming some_val to be a string that might be encoded as bytes.

# Syntax
  • str.capitalize() -> str
  • str.casefold() -> str [only for Python > 3.3]
  • str.center(width[, fillchar]) -> str
  • str.count(sub[, start[, end]]) -> int
  • str.decode(encoding="utf-8"[, errors]) -> unicode [only in Python 2.x]
  • str.encode(encoding="utf-8", errors="strict") -> bytes
  • str.endswith(suffix[, start[, end]]) -> bool
  • str.expandtabs(tabsize=8) -> str
  • str.find(sub[, start[, end]]) -> int
  • str.format(*args, **kwargs) -> str
  • str.format_map(mapping) -> str
  • str.index(sub[, start[, end]]) -> int
  • str.isalnum() -> bool
  • str.isalpha() -> bool
  • str.isdecimal() -> bool
  • str.isdigit() -> bool
  • str.isidentifier() -> bool
  • str.islower() -> bool
  • str.isnumeric() -> bool
  • str.isprintable() -> bool
  • str.isspace() -> bool
  • str.istitle() -> bool
  • str.isupper() -> bool
  • str.join(iterable) -> str
  • str.ljust(width[, fillchar]) -> str
  • str.lower() -> str
  • str.lstrip([chars]) -> str
  • static str.maketrans(x[, y[, z]])
  • str.partition(sep) -> (head, sep, tail)
  • str.replace(old, new[, count]) -> str
  • str.rfind(sub[, start[, end]]) -> int
  • str.rindex(sub[, start[, end]]) -> int
  • str.rjust(width[, fillchar]) -> str
  • str.rpartition(sep) -> (head, sep, tail)
  • str.rsplit(sep=None, maxsplit=-1) -> list of strings
  • str.rstrip([chars]) -> str
  • str.split(sep=None, maxsplit=-1) -> list of strings
  • str.splitlines([keepends]) -> list of strings
  • str.startswith(prefix[, start[, end]]) -> book
  • str.strip([chars]) -> str
  • str.swapcase() -> str
  • str.title() -> str
  • str.translate(table) -> str
  • str.upper() -> str
  • str.zfill(width) -> str
# Remarks

String objects are immutable, meaning that they can’t be modified in place the way a list can. Because of this, methods on the built-in type str always return a new str object, which contains the result of the method call.

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.

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

Вы можете заменить слово или подстроку в строке в программировании на Python. Чтобы заменить String в Python, вы можете использовать метод replace().

Синтаксис

Синтаксис метода replace():

Где, старая строка заменяется новой в строке str количество раз.

Счетчик не является обязательным. Итак, если вы не укажете count, все вхождения старой подстроки будут заменены новой подстрокой.

Пример 1

В следующем примере у нас есть строка. В ней мы заменим строку примеров на строку программ с помощью метода replace().

Пример 2: замена определенное количество раз

В этом примере мы заменим старую строку новой только определенное количество раз.

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

Заключение

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *