I need to create a function that will return all capitalized words from a sentence into a list. If the word ends with a comma, you need to exclude it (the comma). This is what I came up with:
def find_cap(sentence):
s = []
for word in sentence.split():
if word.startswith(word.capitalize()):
s.append(word)
if word.endswith(","):
word.replace(",", "")
return s
My problem: The function seems to work, but if I have a sentence and a word is in quotes, it returns the word in quotes even if it isn't capitalized. Also the commas aren't replaced, even though I used word.replace(",", "")
. Any tips would be appreciated.
Strings are an immutable type in Python. This means that word.replace(",", "")
will not mutate the string word
is pointing at; it will return a new string with the commas replaced.
Also, since this is a stripping problem (and commas are not likely to be in the middle of words), why not use string.strip()
instead?
Try something like this:
import string
def find_cap(sentence):
s = []
for word in sentence.split():
# strip() removes each character from the front and back of the string
word = word.strip(string.punctuation)
if word.startswith(word.capitalize()):
s.append(word)
return s
Use regular expression to do this:
>>> import re
>>> string = 'This Is a String With a Comma, Capital and small Letters'
>>> newList = re.findall(r'([A-Z][a-z]*)', string)
>>> newList
['This', 'Is', 'String', 'With', 'Comma', 'Capital', 'Letters']
using re.findall
:
a= "Hellow how, Are You"
re.findall('[A-Z][a-z]+',a)
['Hellow', 'Are', 'You']
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.