Skip to content Skip to sidebar Skip to footer

How To Test If A String Has Capital Letters

In Scala I could test if a string has a capital letter like this: val nameHasUpperCase = name.exists(_.isUpper) The most comprehensive form in Python I can think of is: a ='asdFgg

Solution 1:

The closest to the Scala statement is probably an any(..) statement here:

any(x.isupper() for x in a)

This will work in using a generator: from the moment such element is found, any(..) will stop and return True.

This produces:

>>>a ='asdFggg'>>>any(x.isupper() for x in a)
True

Or another one with map(..):

any(map(str.isupper,a))

Solution 2:

Another way of doing this would be comparing the original string to it being completely lower case:

>>>a ='asdFggg'>>>a == a.lower()
False

And if you want this to return true, then use != instead of ==

Solution 3:

There is also

nameHasUpperCase = bool(re.search(r'[A-Z]', name))

Post a Comment for "How To Test If A String Has Capital Letters"