Shubham Shrivastava
Shubham Shrivastava

Reputation: 13

TypeError: replace() takes no keyword arguments when we use (old='XYZ',new='ABC')

I was trying string replace function by providing arg_name=VALUE but got TypeError: replace() takes no keyword arguments

>>>s = "shubham shriavstava"

>>>s.replace(old=u"sh", new=u"",count=1)

TypeError: replace() takes no keyword arguments

What is wrong here?

Upvotes: 1

Views: 5515

Answers (2)

benvc
benvc

Reputation: 15120

You are getting the error because str.replace is a built-in implemented in C that cannot take keyword arguments. From the Calls section of the docs:

CPython implementation detail: An implementation may provide built-in functions whose positional parameters do not have names, even if they are ‘named’ for the purpose of documentation, and which therefore cannot be supplied by keyword.

You can resolve the issue by removing the keywords from your function call.

Upvotes: 1

codrelphi
codrelphi

Reputation: 1065

replace(self, old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

Do this:

s = "shubham shriavstava"
new_s = s.replace(u"sh", u"", 1) # same to s.replace("sh", "", 1)
print(new_s)

Output: 'ubham shriavstava'

Upvotes: 0

Related Questions