5

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?

1

3 Answers 3

10

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

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

2
  • 1
    this will certainly work, but it creates a new string (a.lower), which Willem's will avoid by using a generator Jul 28, 2017 at 19:47
  • @JasonStein totally agree, just thought i'd show another way of doing it :)
    – jacoblaw
    Jul 28, 2017 at 19:48
2

There is also

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.