简体   繁体   中英

Python - how to count number of uppercase letters in a string that is in a list

For example, if I have this list:

s = ["Johnny and Annie", "Great job guys", "She and I"]

how can I make Python count the number of uppercase letters in each element of this list? For this example, Python should return 2, 1, 2.

This is my code so far:

def poisci_pare(besedilo):
x = []
seznam = []
t = re.split("[.]", besedilo)
for e in t:
    x = x + e.split()
for s in x:
    if s == s.capitalize() and not s.startswith('"'):
        seznam.append(s)

This function makes a list where it separates sentences by dots and then it filters out all the uppercase words in it, but I've no idea how to make it count the uppercase letters..

Try this:

[sum([c.isupper() for c in a]) for a in s]

for your example it will output:

[2, 1, 2]

a straightforward way could be:

  • loop through each string in your list
  • initialize a counter of upper case letters for the current string
  • loop through each character in the list and check if it isupper
  • update the current string's counter with the number of isupper found

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