簡體   English   中英

在 Python 中為列表的每個元素在 4 個字符后添加一個字符串

[英]Add a string after 4 characters for each element of a list in Python

我有一個列表,其中每個元素都是一個帶有<a>標簽的 url。 我需要在<a>之后和"href="之前為列表的每個元素添加target="_blank"

list = ["<a href=\"url_1\">Title_1</a>", 
    "<a href=\"url_2\">Title_2</a>", 
    "<a href=\"url_3\">Title_3</a>", 
    "<a href=\"url_4\">Title_4</a>"]

我們可以嘗試將列表re.subre.sub一起使用:

output = [re.sub(r'^<a ', '<a target="_blank" ', i) for i in list]
print(output)

['<a target="_blank" href="url_1">Title_1</a>',
 '<a target="_blank" href="url_2">Title_2</a>',
 '<a target="_blank" href="url_3">Title_3</a>',
 '<a target="_blank" href="url_4">Title_4</a>']

這是沒有正則表達式的方法。 @Tim Biegeleisen 解決方案的替代方案。 代碼注釋中的說明:

list = ["<a href=\"url_1\">Title_1</a>",
    "<a href=\"url_2\">Title_2</a>",
    "<a href=\"url_3\">Title_3</a>",
    "<a href=\"url_4\">Title_4</a>"]

new_list = []
# for each html string in the list
for html in list:
    # Create a new string concatenating the first 4 characters of html with  target="_blank"  and the remainder of html string
    s = html[:3] + 'target="_blank" ' + html[3:]
    new_list.append(s)

print(new_list)

另一種選擇是使用map函數來執行target添加:

inlist = ["<a href=\"url_1\">Title_1</a>", 
    "<a href=\"url_2\">Title_2</a>", 
    "<a href=\"url_3\">Title_3</a>", 
    "<a href=\"url_4\">Title_4</a>"]

newList = list(map(lambda elem: elem.replace('<a', '<a target="blank"'), inlist))
print(newList)

輸出:

['<a target="blank" href="url_1">Title_1</a>', '<a target="blank" href="url_2">Title_2</a>', '<a target="blank" href="url_3">Title_3</a>', '<a target="blank" href="url_4">Title_4</a>']

注意:不要使用list作為變量名,因為它是一個保留的 Python 關鍵字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM