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

python check if string contains uppercase
how to convert lowercase to uppercase in python
convert all lowercase letters to uppercase letters and vice versa. in python
print only the uppercase letters in the string python
python capitalize every other letter
how to let python recognize both lower and uppercase input?
python string format capitalize
python split string by character

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.

Python, check how much of a string is in uppercase?, You should use str.isupper() and str.isalpha() function. Eg. is_all_uppercase = word.isupper() and word.isalpha(). According to the docs:. Python string method isupper() checks whether all the case-based characters (letters) of the string are uppercase. Syntax. Following is the syntax for isupper() method − str.isupper() Parameters. NA. Return Value. This method returns true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise. Example

Regex seems overkill here. You can use sum with a generator expression:

x = 'DOFLAMINGO WITH TOUCH SCREEN lorem ipsum'

x_chars = ''.join(x.split())  # remove all whitespace
x_upper = sum(i.isupper() for i in x_chars) > (len(x_chars) / 2)

Or functionally via map:

x_upper = sum(map(str.upper, x_chars)) > (len(x_chars) / 2)

Alternatively, via statistics.mean:

from statistics import mean

x_upper = mean(i.isupper() for i in s if not i.isspace()) > 0.5

Check if any character of a string is uppercase Python, upper() method converts all lowercase characters in a string into uppercase letters · String slicing in Python to check if a string can become empty by recursive  Python Program to check character is Lowercase or Uppercase using islower and isupper functions. In this Python example, we use islower and isupper string functions to check a given character is lowercase or uppercase.

Generic solution that works with any boolean function and iterable (see below for version that only looks at str.isalpha()):

def percentage(data, boolfunc):
    """Returns how many % of the 'data' returns 'True' for the given boolfunc."""
    return (sum(1 for x in data if boolfunc(x)) / len(data))*100

text = "DOFLAMINGO WITH TOUCH SCREEN lorem ipsum"

print( percentage( text, str.isupper ))
print( percentage( text, str.islower ))
print( percentage( text, str.isdigit ))
print( percentage( text, lambda x: x == " " ))

Output:

62.5  # isupper
25.0  # islower
0.0   # isdigit
12.5  # lambda for spaces

even better is schwobaseggl's

return sum(map(boolfunc,data)) / len(data)*100

because it does not need to persist a list but instead uses a generator.


Edit: 2nd version that only uses str.isalpha characters and allows multiple boolfuncs:

def percentage2(data, *boolfuncs):
    """Returns how many % of the 'data' returns 'True' for all given boolfuncs.
    Only uses str.isalpha() characters"""
    return (sum(1 for x in data if all(f(x) for f in boolfuncs)) / sum(
                for x in data if str.isalpha(x)))*100

text = "DOFLAMINGO WITH TOUCH SCREEN lorem ipsum"

print( percentage2( text, str.isupper, str.isalpha ))
print( percentage2( text, str.islower, str.isalpha ))

Output:

71.42857142857143
28.57142857142857

Python, We use the built-in Python method, len(), to get the length of any sequence, on a string converts all of the characters to uppercase, whereas the lower() method  Return value from String upper() The upper() method returns the uppercased string from the given string. It converts all lowecase characters to uppercase. If no lowercase characters exist, it returns the original string.

Using regular expressions, this is one way you can do it (given that s is the string in question):

upper = re.findall(r'[A-Z]', s)
lower = re.findall(r'[a-z]', s)
percentage = ( len(upper) / (len(upper) + len(lower)) ) * 100

It finds the lista of both uppercase and lowercase characters and gets the percentage using their lengths.

Python String Methods: str(), upper(), lower(), count(), To check if a character is upper-case, we can simply use isupper() function call on the said character. exampleprint( 'Z'.isupper()) print( 'u How to check if a character is upper-case in Python? Python Server Side Programming Programming To check if a character is upper-case, we can simply use isupper() function call on the said character.

Here is one way to do it:

f = sum(map(lambda c: c.isupper(), f)) / len(f)
(sum(map(lambda c: c.isupper(), f)) / len(f)) > .50  

How to check if a character is upper-case in Python?, Kite is a free autocomplete for Python developers. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless  In Python, isupper() is a built-in method used for string handling. The isupper() methods returns “True” if all characters in the string are uppercase, Otherwise, It returns “False”. This function is used to check if the argument contains any uppercase characters such as :

How to check if a character is uppercase in Python, The string lower() method converts all uppercase characters in a string into lowercase characters and returns it. Python Program to find character is Uppercase or not. This python program allows a user to enter any character. Next, we are using If Else Statement to check whether the user given character is uppercase or not.

Python String lower(), The string swapcase() method converts all uppercase characters to lowercase and all lowercase characters to uppercase characters of the given string, and  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

Python String swapcase(), See what happens if the first character is a number: txt = "36 is my age." x = txt.​capitalize() print  Python regex to find sequences of one upper case letter followed by lower case letters String slicing in Python to check if a string can become empty by recursive deletion Python | Check if given string can be formed by concatenating string elements of list

Comments
  • Or you could use: statistics.mean(ch.isupper() for ch in s if not ch.isspace())
  • @JonClements, Yep, good point, but a little messier I think because of the if condition.
  • Well, since you're iterating character by character anyway to do the isupper check, I think it's a bit messier to do ''.join(x.split()) to create a new string to iterate over :)
  • ( len(upper) / len(upper) + len(lower) ) == 1 + len(lower)
  • @Patrick Artner, I missed a pair of parenthesis. I'll edit the answer.