首页 > 解决方案 > 关于在 Python 上检查字符类型的问题

问题描述

我目前正在做作业,并且提供了第一行代码并且无法更改。我可以在 PyCharm 中运行,但无法在 Hackerrank 中运行以提交我的作业。

我试图找出我的代码有什么问题,但我认为问题与输入有关。我认为老师希望我们将输入用作变量?

def check_character_type(input):
    # Write your code
    ch = input
    if ch[0].isalpha():
        print("alphabet")
    elif ch[0].isdigit():
        print("digit")
    else:
        print("special")
    return ch

check_character_type(input)

当我在 Hackerrank 中运行代码时,错误消息是

Traceback (most recent call last):
  File "Solution.py", line 29, in <module>
    check_character_type(input)
  File "Solution.py", line 21, in check_character_type
    if ch[0].isalpha():
TypeError: 'builtin_function_or_method' object is not subscriptable

标签: python

解决方案


您在上一个答案中提到的问题并评论说您正在使用名为 input 的函数作为变量的名称...试试这样:

inp = 'test'

def check_character_type(inp):
    # Write your code
    ch = inp
    if ch[0].isalpha():
        print("alphabet")
    elif ch[0].isdigit():
        print("digit")
    else:
        print("special")
    return ch

check_character_type(inp)

输出:

alphabet
'test'

如果“我认为老师希望我们将输入用作变量”,您的意思是您应该事先提供输入,那么首先执行以下操作:

inp = input('Enter the input')

推荐阅读