35

I'm writing a program which does some code generation to python and need to treat a string differently if it is a python keyword. help(keywords) prints the python keywords and some extra stuff, but I wonder if there's a pythonic way to get an actual iterable object with these strings in it?

1

2 Answers 2

80

You are better of using the keyword module

>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
0
16

You can check a specific keyword as well

import keyword
keyword.iskeyword("print") # TRUE

Not the answer you're looking for? Browse other questions tagged or ask your own question.