python 3 : How to check if a string can be a valid variable?

标签 python python-3.x

我有一个字符串,想检查它是否可以用作有效变量而不会出现语法错误。例如

def variableName(string):
    #if string is valid variable name:
        #return True
    #else:
        #return False

input >>> variableName("validVariable")
output >>> True
input >>> variableName("992variable")
output >>> False

我不想使用 .isidentifier()。我想自己做一个函数。

最佳答案

以下答案仅适用于“旧式”Python-2.7 标识符;

"validVariable".isidentifier()
#True
"992variable".isidentifier()
#False

由于您在我发布答案后更改了问题,请考虑编写一个正则表达式:

re.match(r"[_a-z]\w*$", yourstring,flags=re.I)

关于 python 3 : How to check if a string can be a valid variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49331782/

相关文章:

Python 请求 - 尝试获取 presto 文档返回 sslv3 警报握手失败

python - BSON 功能影响性能 - 取决于安装

python - 如何在 python 中的同一图形上以升序绘制压缩列表的前 5 和后 5?

python - Many2one Odoo 11 中的域

python - 如何在 ubuntu 上安装 python 模块 sys、os 和 getopt?

python - 找不到 Python 模块的正确目录

python - 如何将 python 程序转换为 .egg 文件?

python 2 与 3 : Replace list comprehensions with map()?

python - QLineEdit 设置标题大小写

python - pyinstaller ImportError 错误 - 如何解决?