简体   繁体   中英

How to remove words starting with capital letter in a list of strings using re.sub in python

I am using Python and I would like to remove words starting with a capital letter in a list of strings, using re.sub . For example, given the following list:

l = ['I am John','John is going to US']

I want to get the following output, without any extra spaces for the removed words:

['am','is going to']

you can try this:

output = []
for sentence in l:
    output.append(" ".join([word for word in sentence.strip().split(" ") if not re.match(r"[A-Z]",word)]))
print(output)

output:

['am', 'is going to']

You can try

import re

l=['I am John','John is going to US']
print([re.sub(r"\s*[A-Z]\w*\s*", " ", i).strip() for i in l])

Output

['am', 'is going to']

This is a regex that removes all words from a given string that starts with a capital letter in addition it will remove all spaces before and after the word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM