python - 将 print 语句添加到 ValueError 异常

标签 python string function python-2.7 exception

Python 的新手,所以我确定这是一个菜鸟问题,但谷歌搜索并没有给我一个明确的答案。

鉴于以下旨在确保用户输入是字符串的函数,为什么我不能(或我如何)在触发异常时添加打印语句?我在那里插入的打印语句不起作用。

def string_checker(action):
    try:
        check = isinstance(action, basestring)
        if check == True:
            return True
    except ValueError:
        print "We need a string here!"
        return None

action = "words"
string_checker(action)

最佳答案

这可能会做你想做的事:

def string_checker(action):
    try:
        assert isinstance(action, basestring)
        return True
    except AssertionError:
        print "We need a string here!"
        return None

action = "words"
string_checker(action)
string_checker(21)

但您也可以返回“我们这里需要一个字符串!”为了保持一致性,而不是打印它或返回 False。

关于python - 将 print 语句添加到 ValueError 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172252/

相关文章:

string - Unicode 字符串的固定长度存储的正确编码?

arrays - 如何替换字符串中的单个字符?

php - 将 lang 函数放入 php 字符串中

javascript - 如何在 JavaScript 中使用正则表达式获取 2 个字符串之间的内容

python - 在不使用索引的情况下替换 pandas DataFrame 中选定单元格的值

python - 如何将多个 XLSX 文件合并到一个工作簿中,同时保持其工作表独立?

python - "this"模块的源代码是做什么的?

c++ - 如何保持存储在作为参数传递的指针中的地址在所有函数调用中保持一致

java - 如何从 Java Scanner 获取整数输入

python - 模板不存在 at/polls/index.html