Hello. I have a huge question about kwarg.
Cuz in this problem’s answer, key value of kwargs are not string but how can it be change to string?
def remove(filename, *args, **kwargs):
with open(filename) as file_obj:
text = file_obj.read()
for arg in args:
text = text.replace(arg, "")
for kwarg, replacement in kwargs.items():
text = text.replace(kwarg, replacement)
return text
print(remove("text.txt", "generous", "gallant", fond="amused by", Robin="Mr. Robin"))
To rephrase your question, you are wondering why the arguments passed in for **kwargs parameter appear to be variables (rather than strings) and yet the remove function’s text = text.replace(kwarg, replacement) operation still treats the keyword as a string. This is explained by the fact that the unpacked keyword arguments passed to the function are stored by the function as a dictionary (as opposed to unpacked positional arguments which are stored by the function as a tuple). This is illustrated by the example given in the lesson:
A possible call to the function could look like this:
main(“files/users/userslist.txt”,
“-d”,
“-a”,
save_all_records=True,
user_list=current_users)
In the body of main() these arguments would look like this:
Notice at the end the dictionary object has stored the passed arugment save_all_records = True as ‘save_all_records’: True.
It would appear that the purpose of utilizing unpacked keyword arguments is to allow individual key/value pairs to be passed to the function rather than requiring that a dictionary object be passed into the function. You can find more details in the Phython documentation here.
This is driving me crazy because the text file ends up with a grammatical error (highlighted in bold), and I can’t figure out how to remove the “of” after “by” without remove the other “of” in the file.
King Richard often thought upon what he had seen of Mr. Robin Hood and his fellows. He was very amused by of archery; he had heard of many actions that were told about them, and he admired their spirit and manners. Thought he, If I could but make these men my faithful subjects, what a pride they would be to my court! The king at last fixed upon a plan by which he might see Mr. Robin Hood once more.