I've scraped and created a list of URLs and am trying to replace a section of each url in the list.
Each URL contains the section '/season/1288' that I'm trying to remove. 'productions' is my list of urls, and this is the code I was using:
prod_lists = [str.replace('/season/1288', '') for i in productions]
print(prod_lists)
It returns the error
TypeError: replace expected at least 2 arguments, got 1
CodePudding user response:
To make a list using list comprehension
in your code, you should use the variable i, not str
.
productions = [
'/season/1288/aaa',
'/season/1288/bbb',
'/season/1288/ccc',
]
prod_lists = [i.replace('/season/1288', '') for i in productions]
print(prod_lists)
This will print:
['/aaa', '/bbb', '/ccc']
The reason you received the error msg is because you called replace
function using str
class, not str
instance. It automatically passes a str
instance as a first parameter, known as self
but, in this code replace
cannot find a str instance to pass as a first parameter because str
is a class, not an instance.
Interestingly, if you run a following code, explicitly passing str
instance '/season/1288/ccc', you can see the result replaced by 1 without an error msg.
productions = ['/season/1288/aaa']
prod_lists = [str.replace('/season/1288/ccc', '/season/1288', '1') for i in productions]
print(prod_lists) # This prints: ['1/aaa']