[英]How can I identify if there is, at least, one capital letter in Python?
First of all, I'm quite new with Python.首先,我对 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
.我发现
any()
function 会帮助我解决这个问题,但是当我把它放在 function 上时,它返回错误'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
.此外,我已经尝试使用 for 循环,但它返回以下错误
'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.感谢您的帮助,如果需要更多信息,请告诉我。
You can use just map with a isupper function你可以只使用map和isupper function
For example:例如:
s = "abcAs"
contains_upper_case = any(map(str.isupper, s))
print(contains_upper_case)
The any
function should accept an iterable of bool
values, not a single bool
value as returned by x.isupper()
. any
function 应该接受bool
值的迭代,而不是x.isupper()
返回的单个bool
值。 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 [AZ]
to match an uppercase letter:另一种使用正则表达式字符 class
[AZ]
来匹配大写字母的方法:
>>> 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: re.search
function 返回真实的Match
object 或虚假的None
,因此您可以在if
语句中使用它,如下所示:
if re.search('[A-Z]', x):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.