Issue
First of all, I'm quite new with Python.
As the title says, I want to identify if a string contains, at least, one capital letter. If not, I will raise an error saying something like there is no capital letter detected.
I have found that the any()
function would help me with that, but when I put it on the function it returns the error 'bool' object is not iterable
.
Here's what I got:
def identify_capital(x):
if any(x.isupper()) == True:
return True
else:
raise ValueError("No capital letter detected")
Also, I've tried it with a for loop but it returns the following error 'int' object is not subscriptable
. Here's the code:
def identify_capital(x):
for letter in range(len(x)):
if letter[i] in x.isupper():
return True
else:
raise ValueError("No capital letter detected")
Thanks for your help and, if more information is needed, let me know.
Solution
The any
function should accept an iterable of bool
values, not a single bool
value as returned by x.isupper()
. Iterate over the characters in the string:
>>> test1 = 'foo bar'
>>> test2 = 'foo Bar'
>>> any(c.isupper() for c in test1)
False
>>> any(c.isupper() for c in test2)
True
An alternative way using the regex character class [A-Z]
to match an uppercase letter:
>>> import re
>>> re.search('[A-Z]', test1)
>>> re.search('[A-Z]', test2)
<_sre.SRE_Match object; span=(4, 5), match='B'>
The re.search
function returns a truthy Match
object or a falsey None
, so you can use it in an if
statement like so:
if re.search('[A-Z]', x):
...
Answered By - kaya3
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.