python - Try/except 检查字符串

标签 python

我对如何使用 Try/Exceptionif/else 感到困惑。如果我想告诉用户提供.html文件

,我该如何编写惯用代码
if url[-4:] ==".html":
        // do your things
else: 
    print('Error! the file is not html file')

我正在检查我是否应该在这种情况下使用 try/exception 或像我那样使用 if/else

最佳答案

简而言之:

try:
    a = q.get()

try 表示尝试这个东西,如果有效,就使用它,else except 如果它失败了,或者它有效,并且出现诸如 ValueError

except:
    a = None

更新:

try:
   url[-4:] == ".html"

except: 
    print "Error"

关于python - Try/except 检查字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27537780/

相关文章:

python - 我无法通过查询获取实体

python - 使用 sqlalchemy 库时如何捕获访问被拒绝错误?

python - 如何将字典列表的数组合并为一个字典

python - 如何在Python中的列表排序中获得正确的结果

python - 与 tkinter 同时使用 .pack() 和 .grid()

python - 解决在 python 中打开 pdf 文件时的路径问题

python - 在不呈现重定向页面的情况下进行重定向

Python:无法使用 vs code 进行调试

python - 我需要帮助制定特定的正则表达式

python - 使用 Python 在 PDF 中搜索文本?