-2

Implement filescounter, which takes a string in any variety and returns the number of capitalized words in that string, inclusive of the last and first character.

def filescounter(s):
    sr=0
    for words in text:
        #...
    return sr

I'm stuck on how to go about this.

Nosrep
  • 521
  • 7
  • 21
  • Use Regular Expression https://docs.python.org/3/howto/regex.html#:~:text=Regular%20expressions%20%28called%20REs%2C%20or%20regexes%2C%20or%20regex,addresses%2C%20or%20TeX%20commands%2C%20or%20anything%20you%20like. – Joel Chu Nov 11 '20 at 01:54
  • Does this answer your question? [Counting Upper Case words in a variable in python](https://stackoverflow.com/questions/49078267/counting-upper-case-words-in-a-variable-in-python) – Nosrep Nov 11 '20 at 02:10
  • Please read the following: https://stackoverflow.com/help/how-to-ask – Mad Physicist Dec 03 '20 at 21:16
  • Stack overflow is not a place to dump your homework questions. – Mad Physicist Dec 03 '20 at 21:16

2 Answers2

1

Split the text on whitespace then iterate through the words:

def countCapitalized(text):
    count = 0
    for word in text.split():
        if word.isupper():
            count += 1
    return count

If, by capitalized, you mean only the first letter needs to be capitalized, then you can replace word.isupper() with word[0].isupper().

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • 1
    First of all, "does this work" isn't a good question. Just test it yourself and see if it does. Second of all, `split` splits on all whitespace by default, including newlines. – Aplet123 Nov 11 '20 at 00:35
1

Use this:

def count_upper_words(text):
    return sum(1 for word in text.split() if word.isupper())

Explanation:

  • split() chops text to words by either spaces or newlines
  • so called list comprehension works faster than an explicit for-loop and looks nicer
Kroshka Kartoshka
  • 1,035
  • 5
  • 23