How to use function replace in Python? - with practical example
When working with strings in Python, the replace function is a useful method that allows you to replace occurrences of a specified substring within a string with another substring.
Example 1:
Let's say we have a string that contains the word "hello" and we want to replace it with "hi".
Explaining:
1. Define a string variable containing the word "hello".
2. Use the replace function to replace "hello" with "hi".
3. Print the modified string to see the result.
Code:
Example 2: Now, let's consider a scenario where we have a sentence with multiple occurrences of a word that we want to replace. Explaining: 1. Create a string variable with a sentence containing the word "Python" multiple times. 2. Use the replace function to replace all occurrences of "Python" with "Java". 3. Print the modified sentence to see the changes. Code:
By using the replace function in Python, you can easily manipulate strings by replacing specific substrings with desired values. This can be particularly useful when you need to modify text data within your programs.
# Define the original string original_string = "hello world" # Replace "hello" with "hi" modified_string = original_string.replace("hello", "hi") # Print the modified string print(modified_string)
Example 2: Now, let's consider a scenario where we have a sentence with multiple occurrences of a word that we want to replace. Explaining: 1. Create a string variable with a sentence containing the word "Python" multiple times. 2. Use the replace function to replace all occurrences of "Python" with "Java". 3. Print the modified sentence to see the changes. Code:
# Define the original sentence original_sentence = "I love Python programming. Python is a great language." # Replace all occurrences of "Python" with "Java" modified_sentence = original_sentence.replace("Python", "Java") # Print the modified sentence print(modified_sentence)
By using the replace function in Python, you can easily manipulate strings by replacing specific substrings with desired values. This can be particularly useful when you need to modify text data within your programs.
Comments
Post a Comment