学习 python 并使用一些基本的字符串方法。
我有这个程序可以找到字符串中第一个小写字符的索引:
def find_lower(word):
i = 0
while not isupper(word[i]):
i = i+1
return i
但是,当我运行此代码时,出现错误
builtins.NameError: name 'isupper' is not defined
我需要导入模块或其他东西isupper()
才能工作吗?
您使用isupper
不当。它不是内置的独立功能。它是 的一种方法str
。文档在这里。
对于您不确定的任何函数,您可以查阅 python 文档。它被谷歌很好地索引,所以当你想了解如何使用一个函数时,谷歌搜索是一个很好的起点。
一旦解决了这个问题,您就会find_lower
遇到更多问题。由于逻辑错误,它实际上找到了第一个大写字母的索引。
while not word[i].isupper():
如果字符不是大写,则继续循环,如果是则停止。所以你需要删除not
.
def find_lower(word):
i = 0
while word[i].isupper():
i = i+1
return i
print(find_lower('ABcDE')) # prints 2
下一个错误是,如果没有小写字符,它会离开字符串的末尾并抛出异常
>print(find_lower('ABCDE'))
Traceback (most recent call last):
File "./myisupper.py", line 11, in <module>
print(find_lower('ABCDE'))
File "./myisupper.py", line 5, in find_lower
while word[i].isupper():
IndexError: string index out of range
要解决这个问题,您需要将迭代次数限制为字符串的长度,这留作练习来解决。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句