TypeError: str.replace() takes no keyword arguments (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: str.replace() takes no keyword arguments (Python) #

The Python "TypeError: str.replace() takes no keyword arguments" occurs when we pass keyword arguments to the str.replace() method. To solve the error, pass only positional arguments to replace(), e.g. my_str.replace('old', 'new').

python str replace takes no keyword arguments

Here is an example of how the error occurs.

main.py
my_str = 'apple, apple, banana' # ⛔️ TypeError: str.replace() takes no keyword arguments result = my_str.replace(old='apple', new='kiwi')

The error was caused because we passed keyword arguments to the replace() method.

The replace() method takes only positional arguments.

main.py
my_str = 'apple, apple, banana' result = my_str.replace('apple', 'kiwi') print(result) # 👉️ kiwi, kiwi, banana

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

Note that the method doesn't change the original string. Strings are immutable in Python.

If you need to use a regular expression when replacing characters in a string, use the re.sub method.

main.py
import re my_str = '1apple, 2apple, 3banana' result = re.sub(r'[0-9]', '_', my_str) print(result) # 👉️ _apple, _apple, _banana

The re.sub method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

If the pattern isn't found, the string is returned as is.

Conclusion #

The Python "TypeError: str.replace() takes no keyword arguments" occurs when we pass keyword arguments to the str.replace() method. To solve the error, pass only positional arguments to replace(), e.g. my_str.replace('old', 'new').

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.