Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a word using regex wont work

Tags:

python

regex

Post text is a list of tweets. I want to replace url adresses in every tweet with "URL". But when i print "post_text", i see nothing is changed, although when i print "tweet" i see that it has been replaced. How can replace url adresses in post_text???

for tweet in post_text:
    tweet=re.sub(r'http\S*', "URL", tweet)

1 Answers

This problem is happening as your tweet variable is a new variable which is never assigned back to the list.

Try using a list comprehension instead:

post_text = [re.sub(r'http\S*', "URL", tweet) for tweet in post_text]

Or you can use enumerate to use the item index during the loop. This is recommended if you have a more complicated loop than what is in the question:

for i, tweet in enumerate(post_text):
    post_text[i] = re.sub(r'http\S*', "URL", tweet)
like image 127
Milk Avatar answered May 08 '26 00:05

Milk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!