Recalling strings: String is a data type in python which is used to store words or sentences in a variable, for example. a = “I am a python programmer”. In this example I am a programmer I s a sentence stored in a string “ a “ . Now we can assign sentence to any variable to store string such as a, b, c ,num etc. But there are some words which are prohibited to be used to store any data in them. What are they? Let us understand keywords first.
Keywords are reserved words that are assigned a special task or function by the compiler. They are necessary part of a programming language. Keywords cannot be used a variable to store any data type either int, string or others. The reason is that keywords have already defined functionality inside the compiler, and they have their task assigned already so cannot be over looped. For is a reserved keyword to use for loop. Let us see on the compiler
It did not display value for “I am a python programmer” because it was stored in a reserved keyword. According to askpython.com there are 35 keywords in python.
Check if string is valid
Now we will see through an example that if you are using some variable as a string either it is reserved keyword or it is valid to be used.
Import keyword library in python compiler, it will be used to distinguish keywords from variables we will assign. This can be done using.
Create a function using def checkFunction. Pass string inside its parameter for which you want to check is valid or not.
Compare list of keywords with the one you are trying to check using.
keyword_list = keyword.kwlist
if mystring in keyword_list :
return “It is a reserved keyword”
return “It is a valid string
Simply add you desired string to be checked inside parameter for this function.
print(checkFunction(“Your string that you want to check “))
Step5: Final code
- import keyword
- def checkFunction(mystring) :
- keyword_list = keyword.kwlist
- if mystring in keyword_list :
- return “It is a reserved keyword”
- else :
- return “It is a valid string”
Total Keywords in python
False break for not
None class from or
True continue global pass
__peg_parser__ def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
Software engineer| technical writer and a cybersecurity enthusiast
- How To Deal With Massive Tooling Upgrades In Giant Organizations — Smashing Journal
- This AI Analysis Introduces a Deep Studying Mannequin that may Steal Knowledge by Listening to Keystrokes Recorded by a close-by Telephone with 95% Accuracy
- Educating Children Programming – Ok Objects With the Most Sum
- This AI Paper Introduces the Phase Something for NeRF in Excessive High quality (SANeRF-HQ) Framework to Obtain Excessive-High quality 3D Segmentation of Any Object in a Given Scene.