Python Lab · Experiment 21
Capitalize the first letter of every word without built-in functions
PythonWeek 4JNTUH R22 · CS206ES
Aim
To write a Python function that takes a sentence and returns it with the first letter of every word in uppercase and the other letters of each word in lowercase, changing the case with character codes instead of string methods such as upper(), lower() or title().
Algorithm
- Define the function capitalize_words(sentence). Start with an empty result string and a flag
start_of_wordset to True. - For each character ch of the sentence:
- If ch is a space, add it to the result and set
start_of_wordto True. - Otherwise, if it is the start of a word and ch is between 'a' and 'z', change it to uppercase with
chr(ord(ch) - 32). - If it is not the start of a word and ch is between 'A' and 'Z', change it to lowercase with
chr(ord(ch) + 32). - Add the character to the result and set
start_of_wordto False. - Return the result. In the main program, read a sentence and print the converted sentence.
Program
def capitalize_words(sentence):
"""First letter of each word in uppercase, the rest in lowercase."""
result = ""
start_of_word = True
for ch in sentence:
if ch == " ":
result += ch
start_of_word = True
continue
if start_of_word and "a" <= ch <= "z":
ch = chr(ord(ch) - 32) # 'a' (97) -> 'A' (65)
elif not start_of_word and "A" <= ch <= "Z":
ch = chr(ord(ch) + 32) # 'A' (65) -> 'a' (97)
result += ch
start_of_word = False
return result
text = input("Enter a sentence: ")
print("Converted:", capitalize_words(text))Output
Mixed case words
Enter a sentence: hELLO wORLD from pYTHON
Converted: Hello World From PythonExtra spaces and digits
Enter a sentence: the 2nd LAB record
Converted: The 2nd Lab RecordRecorded by running this exact program. Typed input appears after each prompt.
How it works
The syllabus asks for this "without using a built-in function", but no program can avoid built-ins completely: even len, ord, chr and print are built-in functions. This program takes it to mean that the case-changing string methods (upper, lower, capitalize, title) are not used, and the case is changed by hand.
In ASCII and Unicode, every lowercase English letter has a code exactly 32 more than its uppercase letter: 'A' is 65 and 'a' is 97. So subtracting 32 from the code of a lowercase letter gives the uppercase letter, and adding 32 goes the other way.
Characters that are not letters, such as digits, are copied unchanged. In the second run, "2nd" stays "2nd" because the word starts with a digit. Spaces are kept exactly as they were, including extra spaces.
Common mistakes
Subtracting 32 from every first character, including digits and capital letters. Check that the character is between 'a' and 'z' first, or a digit such as '2' turns into an unprintable control character.
Not resetting the flag after a space, so only the very first word is capitalized.
Splitting with
split()and joining with one space. That loses extra spaces in the original sentence; going character by character keeps them.Using
ch.upper()orsentence.title(), which the experiment asks you not to use.
Viva questions
Try to answer each one aloud before you open it.
What do ord and chr do?
ord(ch)gives the integer code of a character, for exampleord("a")is 97.chr(n)does the reverse, sochr(65)is"A".Why does subtracting 32 change a lowercase letter to uppercase?
The codes of 'a' to 'z' (97 to 122) are exactly 32 more than the codes of 'A' to 'Z' (65 to 90).
Why can't we change the characters of the string in place?
Strings are immutable in Python. The function builds a new result string one character at a time.
How does the program know a character is the first letter of a word?
It keeps a flag that is set to True at the start and after every space, and set to False after any other character.
What would the built-in title() method give for "hELLO wORLD"?
"Hello World", the same result as this function for plain words.