首页 > 解决方案 > 我如何知道用户输入是否包含python中的所有字符或数字

问题描述

我正在使用 PyCharm,并希望知道如何设置我的字符串/变量来告诉我用户输入是全字母字符还是全数字?这是一个伪代码示例:

weak = all characters or numbers
strong = a mix of characters and numbers

INPUT password

'isaplpha' 或 'isnumeric' 可以在这种情况下派上用场吗?如果是这样,怎么做?

标签: pythonpycharm

解决方案


是的!你是对的,isalpha正是isnumeric你想要的。

第一次测试

what = 'letters'
if what.isalpha():
    print('only letters')
elif what.isnumeric():
    print('only numbers')

输出

'only letters'

第二次测试

what = "123" 
if what.isalpha():
    print('only letters')
elif what.isnumeric():
    print('only numbers')

输出

only numbers

推荐阅读