Python replacing characters in strings

Python: Replace a character in a string

In this article, we will discuss different ways to replace a character in string in python.

Overview:

Replace all occurrences of a character in string in python using replace()

In python, the String class (Str) provides a method replace() to replace the sub-strings in a string. We can use that to replace all the occurrences of a character in a string with another character. For example,

org_string = "This is a sample string" # Replace all occurrences of a character in string in python new_string = org_string.replace('s', 'X') print(new_string)

Here we passed the character to be replaced ‘s’ as the first argument and character ‘X’ as the second argument. Then replace() method returned a copy of the original string by replacing all the occurrences of character ‘s’ with the ‘X’.

Frequently Asked:

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

Replace the first two occurrences of a character in string in python

Instead of replacing all occurrences of a character in a string, we can replace only the first few occurrences of a character in a string by passing the count argument in the replace() function i.e.

org_string = "This is a sample string" # Replace first two occurrences of a character in string new_string = org_string.replace('s', 'X', 2) print(new_string)

Here we passed the character to be replaced ‘s’ as the first argument and character ‘X’ as the second argument. Then we passed the third argument as 2. The third argument is optional and it tells the replace() function that how many occurrences of given sub-string need to be replaced.

Читайте также:  Android command line java

Then replace() method returned a copy of the original string by replacing only first two occurrences of ‘s’ with the ‘X’.
As strings are immutable in Python, i.e., we cannot change its contents. Therefore replace() function returns a copy of the string with the replaced content.

Replace a character in a string using regex in python

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 all occurrences of a character in the string,

import re # Replace a character in string using regex in python new_string = re.sub('s', 'X', org_string) print(new_string)

Here we passed the character to be replaced ‘s’ as the first argument and character ‘X’ as the second argument in the sub() function. Then we passed the third argument as the original string.

Sub() function used the first argument as a pattern and replaced all the matches of that pattern with the given replacement string, i.e., ‘X’. So, it replaced all the occurrences of character ‘s’ with the character ‘X’. As strings are immutable in python i.e., we cannot change its contents. Therefore sub() function of the regex module returns a copy of the string with the replaced content.

Replace a character in a string using for loop in python

Initialize an empty string and then iterate over all characters of the original string. During iteration, add each character to the new string. But for the characters that needs replacement, use the replacement character instead. For example,

to_replace = 's' replaced = 'X' # Replace a character in string using for loop new_string = '' for elem in org_string: if elem == to_replace: new_string += replaced else: new_string += elem print(new_string)

It replaced all the occurrences of character ‘s’ with the ‘X’.

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

We can replace a character in a string with another character in python by using the replace() function or sub() function or a for loop.

Share your love

Leave a Comment Cancel Reply

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

Читайте также:  Most common в питоне

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.

Источник

Python string.replace() – How to Replace a Character in a String

Dillion Megida

Dillion Megida

Python string.replace() – How to Replace a Character in a String

Python has numerous string modifying methods, and one of them is the replace method.

In this article, I’ll show you how this method can be used to replace a character in a string.

How the replace Method Works in Python

The replace string method returns a new string with some characters from the original string replaced with new ones. The original string is not affected or modified.

Читайте также:  Javascript math no rounding

The syntax of the replace method is:

string.replace(old_char, new_char, count) 

The old_char argument is the set of characters to be replaced.

The new_char argument is the set of characters that replaces the old_char .

The count argument, which is optional, specifies how many occurrences will be replaced. If this is not specified, all occurrences of the old_char will be replaced with the new_char .

string.replace() Examples

Here’s an example that replaces «JavaScript» with «PHP» in a string:

str = "I love JavaScript. I prefer JavaScript to Python because JavaScript looks more beautiful" new_str = str.replace("JavaScript", "PHP") print(new_str) # I love PHP. I prefer PHP to Python because PHP looks more beautiful 

You can see how the replace method replaces the «JavaScript» occurences with «PHP».

In this example, the three occurrences of «JavaScript» are replaced with «PHP». What if you wanted only one occurrence to be replaced? Then you can use the count argument like this:

str = "I love JavaScript. I prefer JavaScript to Python because JavaScript looks more beautiful" new_str = str.replace("JavaScript", "PHP", 1) print(new_str) # I love PHP. I prefer JavaScript to Python because JavaScript looks more beautiful 

By applying a count argument of 1, you can see that only the first «JavaScript» (the first occurrence) is replaced with «PHP». The remaining «JavaScript»s stays untouched.

When to Use the replace Method in Python

A good use case of this method is to replace characters in a user’s input to fit some standard.

Let’s say, for example, you want users to enter their usernames but you don’t want the whitespace character in the username input. You can use the replace method to replace the whitespaces in the submitted strings with a hyphen. Here’s how to do that:

user_input = "python my favorite" updated_username = user_input.replace(" ", "-") print(updated_username) # python-my-favorite 

From the result of the replace method, you can see that the whitespaces have been replaced with hyphens which meets your standard.

Wrapping Up

The replace method replaces an existing substring in a string with a new substring. You specify how many occurrences of the existing substring are to be replaced with the count argument of the method.

Источник

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