In this source code example, we will demonstrate how to use the Python string replace() method to replace some or all occurrences of a substring with a new substring.
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.The following example uses the replace() method to replace the first occurrence of the substring:
Python
Python String
Python string replace() method example
The following example uses the string replace() method to replace all occurrences of the substring 'C' with the new substring 'Python':s = 'C programming is a top programming language'
new_s = s.replace('C', 'Python')
print(s)
print(new_s)
s1 = 'C is a OOP language'
new_s1 = s1.replace('C', 'Python')
print(s1)
print(new_s1)
Output:
C programming is a top programming language
Python programming is a top programming language
C is a OOP language
Python is a OOP language
s = 'Python Python source code examples'
new_s = s.replace('Python', 'The', 1)
print(s)
print(new_s)
Output:
Python Python source code examples
The Python source code examples
Related Python String Examples
- Python string literals
- Python string length example
- Python String join() method example
- Python string split() method example
- Python String index() method example
- Python string find() method example
- Python string startswith() method example
- Python string endswith() method example
- Python String lower() method example
- Python String upper() method example
- Python string title() method example
- Python string capitalize() method example
- Python string islower() method example
- Python string istitle() method example
- Python string isupper() method example
- Python string swapcase() method example
- Python string strip() method example
- Python string replace() method example
- Python string isdigit() method example
- Python string isdecimal() method example
- Python string isnumeric() method example
- Python string isalpha() method example
- Python string isalnum() method example
Comments
Post a Comment