I want to delete a specific word from the Python string.

Asked 2 years ago, Updated 2 years ago, 76 views

list = [(10) Hello,

Today's weather is cold (43423)

(apple) It's very cold]

There's a string list like this. I want to delete all the strings in here, including parentheses.

I wrote the re module like the code below.

import re

a_list = ['(10) Hello', 'Today's weather is cold(43423)', '(apple) Very cold']

p = re.compile('(.)')

for i in range(len(a_list)):
    real_text = re.sub(p, "", a_list[i])
    a_list[i] = real_text

print(a_list)

I expected the result to be [Hello, Today's Weather, Very Cold]

The resultant is ["", "", "".

What should I do to make it come out the way I thought?

python regex

2022-09-22 15:55

1 Answers

Try LAZY QUANTIFIER (*?

import re

a_list = ['(10) Hello', 'Today's weather is cold(43423)', '(apple) Very cold']

p = re.compile('\(.*?\)')

for i in range(len(a_list)):
    real_text = re.sub(p, "", a_list[i])
    a_list[i] = real_text

print(a_list)


2022-09-22 15:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.