[英]How can I edit strings/urls within a list?
I've scraped and created a list of URLs and am trying to replace a section of each url in the list.我已经抓取并创建了一个 URL 列表,并试图替换列表中每个 url 的一部分。
Each URL contains the section '/season/1288' that I'm trying to remove.每个 URL 都包含我要删除的“/season/1288”部分。 'productions' is my list of urls, and this is the code I was using:
'productions' 是我的 url 列表,这是我使用的代码:
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
To make a list using list comprehension
in your code, you should use the variable i, not str
.要在代码中使用
list comprehension
来制作列表,您应该使用变量 i 而不是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.您收到错误消息的原因是因为您使用
str
类而不是str
实例调用了replace
函数。 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.它自动将
str
实例作为第一个参数传递,称为self
但是,在此代码中, replace
找不到 str 实例作为第一个参数传递,因为str
是一个类,而不是一个实例。
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.有趣的是,如果您运行以下代码,明确传递
str
instance '/season/1288/ccc',您可以看到结果被 1 替换,而不会出现错误 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.