[英]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.