Python, check how much of a string is in uppercase?

  • A+
Category:Languages

I have a text, and I want to know if all or a percent bigger than 50% is in uppercase.

DOFLAMINGO WITH TOUCH SCREEN lorem ipsum

I try to use regex(found here a solution):

rx = re.compile(r"^([A-Z ':]+$)", re.M) upp = rx.findall(string) 

But this finds all caps, i don't know if all or more than 50 percent(this includes all) is uppercase ?

I want to number only letters (so no numbers,spaces, new lines etc)

 


You can use filter and str.isalpha to clean out non-alphabetic chars and str.isupper to count uppercase chars and calculate the ratio:

s = 'DOFLAMINGO WITH TOUCH SCREEN lorem ipsum'  alph = list(filter(str.isalpha, s))  # ['D', ..., 'O', 'W', ..., 'N', 'l', 'o', ...] sum(map(str.isupper, alph)) / len(alph) # 0.7142857142857143 

Also see the docs on sum and map which you might find yourself using regularly. Moreover, this uses the fact that bool is a subclass of int and is cast appropriately for the summation which might be too implicit for the taste of some.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: