Camelcase notation is a style of naming variables in your program where every word that makes up your variable is written with an uppercase letter. For instance, “ThisIsACamelCaseString” is in camelcase but “thisisacamelcasecasestring” is not in camelcase.
There are many interpretations of what constitutes CamelCase but here we assume that i) the string must begin with a capital letter, ii) every word in the string must also begin with a capital letter, iii) there are no numbers or special characters in it.
One easy way to check if a Python string is in CamelCase is to use the “re” (regular expression) module. We will import this module, construct a suitable pattern, and use the match() function in “re” to detect if the input string matches the pattern.
Here is a program to do so:
Note that the pattern is anchored with “^” (for beginning of the string) and “$” (for end of the string). Within these two anchors, we see that we are looking for multiple occurrences of “[A-Z][a-z]+”. (The multiple occurrences are denoted by the asterisk - “*”). The “[A-Z]” ensures that the part begins with an uppercase letter. The “[a-z]+” ensures that after the capital letter, we get one or more occurrences of a lowercase letter.
Let us try this program out:
The output is:
The first two examples are true CamelCase strings. The last example string has no upper case letters, and thus the test fails.
Note that in the above code, an empty string is considered a valid example of CamelCase. If we do:
we will get:
If we wish to disallow such cases, we can replace the “*” with “+” in the original regular expression, like so:
This program will output:
Note that the program has no understanding of “words”, i.e., which sequence of characters forms a word and when a new word begins. So if we try:
we will get:
because Python thinks that there is only one word, namely “Kodeclikonlineacademy” and has no understanding that “Kodeclik”, “online”, and “academy” are separate words.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.