簡體   English   中英

在python的一行代碼中替換字符串中的多個鏈接

[英]Replacing multiple links in a string in one line of code in python

我是正則表達式模塊的新手。 我正在嘗試刪除給定exampleString中的所有鏈接,但要刪除一行代碼:

exampleSentence = exampleSentence.replace(link for link in re.findall(r'http://*',exampleSentence),'')

但是我收到此語法錯誤:

SyntaxError: Generator expression must be parenthesized if not sole argument

如何進行呢?

你有很多問題。

首先, str.replace()在給定字符串中用另一個子字符串替換子字符串; 它不需要發電機。

例:

print 'example'.replace('e', 'E')

接下來,如果要刪除,則有re.sub()

data = re.sub(
  r'[A-Za-z]+://[A-Za-z0-9-_]+.[A-Za-z0-9-_:%&;\?#/.=]+', # the URI
  '', # the replacement (nothing here)
  input_data
)

URI正則表達式是從@ miko-trueman answer復制的。

如果您要做的就是從字符串中刪除所有鏈接,則不需要生成器。 以下將起作用。

import re
exampleString = "http://google.com is my personal library. I am not one for http://facebook.com, but I am in love with http://stackoverflow.com"
exampleString = re.sub(r"(?:\@|https?\://)\S+", '', exampleString)

暫無
暫無

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

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