furoscame
furoscame

Reputation: 129

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 ='asdFggg'
functools.reduce(lambda x, y: x or y, [c.isupper() for c in a])
->True

Somewhat clumsy. Is there a better way to do this?

Upvotes: 6

Views: 6832

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

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))

Upvotes: 10

Gribouillis
Gribouillis

Reputation: 2220

There is also

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

Upvotes: 2

jacoblaw
jacoblaw

Reputation: 1283

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 ==

Upvotes: 4

Related Questions