Python program to capitalize all characters of a string without using inbuilt functions

Python program to capitalize all characters of a string without using an inbuilt function:

In this post, we will write one python program to capitalize all characters of a string. It will not use any inbuilt method for that. So, the python script will take one string as input from the user, capitalize all characters of the string and print out the final string.

Algorithm:

We will use the ASCII values of characters to do the conversion.

  • ASCII value of A is 65
  • ASCII value of a is 97. All other characters are in serial order. The difference is 97 - 65 = 32.
  • So, to convert a character from lowercase to uppercase, we need to subtract 32 from its ASCII value. We can find the ASCII value and convert that value to character using chr() method.
  • The program will create one empty result string intially. For lowercase characters, it will convert it to uppercase and add it to the result string. For any other character, which is not a lowercase character, we will directly add that to the final string.

Python program:

Below is the complete python program:

given_string = input("Enter a string:")
result_string = ''

for ch in given_string:
    current_ascii = ord(ch)
    if current_ascii in range(97, 123):
        result_string += chr(current_ascii - 32)
    else:
        result_string += ch

print('Final string : {}'.format(result_string))

Here,

  • It is taking the string as input from the user and storing it in given_string.
  • We are creating one empty string to hold the result, result_string.
  • Using a for loop, it is iterating throught the characters of the string given_string one by one.
  • For each character, it is reading the ASCII value using ord(). This value is stored in the variable current_ascii.
  • If this ASCII value, current_ascii is in range of 97 to 122, i.e. if the current character is a lowercase character, it decrements this value by 32 and converts this value to character using chr. This character is appended to the string result_string.
  • If the character is not a lower case character, it is appending that character to the string result_string.
  • Once the for loop ends, it is printing the final value of result_string.

Output:

This program will print output as like below:

Enter a string:abcdefghijklmnopqrstuvwxyz
Final string : ABCDEFGHIJKLMNOPQRSTUVWXYZ

Enter a string:abcdEFGH
Final string : ABCDEFGH

Enter a string:abcdEFGH1234#@$
Final string : ABCDEFGH1234#@$

Enter a string:hello World
Final string : HELLO WORLD

python capitalize characters

You might also like: