Python String replace() Method
The string replace() method in Python is a built-in string method used to replace all occurrences of a substring within a string with another substring.
Syntax:
- string: the original string to be modified
- old_substring: the substring to be replaced
- new_substring: the substring to replace old_substring
- count (optional): the number of occurrences of old_substring to be replaced.
Following are some examples of the replace() method in action:
Replace a single occurrence of a substring within a string
In the above example, the replace() method replaces the first occurrence of "World" with "Python" in the string.
Replace all occurrences of a substring within a string
In the above example, the replace() method replaces all occurrences of "the" with "a" in the string.
Limit the number of occurrences to replace using the count parameter
In the above example, the replace() method replaces the first occurrences of "the" with "a" in the string.
Replace a single character within a string
In the above example, the replace() method replaces all occurrences of "o" with "0" in the string.
Replace a substring with an empty string to remove it from the original string
In the above example, the replace() method replaces the substring ", " (a comma followed by a space) with an empty string, effectively removing it from the original string.
String in Python
In Python, a string is a sequence of characters enclosed in either single quotes ('...') or double quotes ("..."). Python treats both single quotes and double quotes the same way, so you can use either type to define a string. If you need to use a quote inside a string that's enclosed in the same type of quotes, you can use the other type of quotes to define the string.
Strings are immutable in Python, which means that you cannot change individual characters within a string. However, you can create a new string by concatenating two or more strings using the + operator. You can also access individual characters within a string using indexing.
Commonly used string methods
Following are some commonly used string methods in Python:
- str.upper(): Returns a copy of the string with all the characters converted to uppercase.
- str.lower(): Returns a copy of the string with all the characters converted to lowercase.
- str.strip(): Returns a copy of the string with leading and trailing whitespace removed.
- str.isdigit(): Returns True if all the characters in the string are digits, and False otherwise.
- str.isalnum(): Returns True if all the characters in the string are alphanumeric (letters or digits), and False otherwise.
- str.isalpha(): Returns True if all the characters in the string are alphabetic, and False otherwise.
- str.islower(): Returns True if all the cased characters in the string are lowercase, and there is at least one cased character in the string, and False otherwise.
- Python print statement "Syntax Error: invalid syntax"
- Installing Python Modules with pip
- How to get current date and time in Python?
- No module named 'pip'
- How to get the length of a string in Python
- ModuleNotFoundError: No module named 'sklearn'
- ModuleNotFoundError: No module named 'cv2'
- Python was not found; run without arguments
- Attempted relative import with no known parent package
- TypeError: only integer scalar arrays can be converted to a scalar index
- A value is trying to be set on a copy of a slice from a DataFrame
- ValueError: setting an array element with a sequence
- Indentationerror: unindent does not match any outer indentation level
- Valueerror: if using all scalar values, you must pass an index
- ImportError: libGL.so.1: cannot open shared object file: No such file or directory
- Python Try Except | Exception Handling
- Custom Exceptions in Python with Examples
- sqrt Python | Find the Square Root in Python
- Read JSON file using Python
- Binary search in Python
- Defaultdict in Python
- Int Object is Not Iterable – Python Error
- os.path.join in Python
- TypeError: int object is not subscriptable
- Python multiline comment
- Typeerror: str object is not callable
- Python reverse List
- zip() in Python for Parallel Iteration
- strftime() in Python
- Typeerror: int object is not callable
- Python List pop() Method
- Fibonacci series in Python
- Python any() function
- Python any() Vs all()
- Python pass Statement
- Python Lowercase - String lower() Method
- Modulenotfounderror: no module named istutils.cmd
- Append to dictionary in Python : Key/Value Pair
- timeit | Measure execution time of small code
- Python Decimal to Binary
- GET and POST requests using Python
- Difference between List VS Set in Python
- How to Build Word Cloud in Python?
- Binary to Decimal in Python
- Modulenotfounderror: no module named 'apt_pkg'
- Convert List to Array Python