[英]How can I identify if there is, at least, one capital letter in Python?
首先,我对 Python 很陌生。
正如标题所说,我想确定一个字符串是否至少包含一个大写字母。 如果没有,我会提出一个错误,说没有检测到大写字母。 我发现any()
function 会帮助我解决这个问题,但是当我把它放在 function 上时,它返回错误'bool' object is not iterable
。
这是我得到的:
def identify_capital(x):
if any(x.isupper()) == True:
return True
else:
raise ValueError("No capital letter detected")
此外,我已经尝试使用 for 循环,但它返回以下错误'int' object is not subscriptable
。 这是代码:
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")
感谢您的帮助,如果需要更多信息,请告诉我。
你可以只使用map和isupper function
例如:
s = "abcAs"
contains_upper_case = any(map(str.isupper, s))
print(contains_upper_case)
any
function 应该接受bool
值的迭代,而不是x.isupper()
返回的单个bool
值。 遍历字符串中的字符:
>>> test1 = 'foo bar'
>>> test2 = 'foo Bar'
>>> any(c.isupper() for c in test1)
False
>>> any(c.isupper() for c in test2)
True
另一种使用正则表达式字符 class [AZ]
来匹配大写字母的方法:
>>> import re
>>> re.search('[A-Z]', test1)
>>> re.search('[A-Z]', test2)
<_sre.SRE_Match object; span=(4, 5), match='B'>
re.search
function 返回真实的Match
object 或虚假的None
,因此您可以在if
语句中使用它,如下所示:
if re.search('[A-Z]', x):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.