Example HTML page

A Python program to print initials/first letters in a string.

The following program prints the first letters of the string and returns those letters in uppercase.

#Program

def Initials(str):  
    if(len(str) == 0): 
        return
    print(str[0].upper( )) 
    for i in range(1, len(str)): 
        if (str[i] == ' '): 
            print (str[i + 1].upper( ))
str = "paint yellow to halloween on net"
Initials(str)

Output

P

Y

T

H

O

N

 We can also write the above program without using if condition which is outside the for loop. It is as follows:

def Initials(str):  
    a=str[0].upper( )
    print(a)
    for i in range(1, len(str)): 
        if (str[i]==' '): 
            print (str[i + 1].upper( ))
str = "paint yellow to halloween on net"
Initials(str)

Output

P

Y

T

H

O

N

Explanation

In the above program ‘Initials’ is the function definition with ‘str’ as a parameter in it. The statement ‘str[0].upper( )’evaluates the zeroth index position of an element in a  string and by using ‘upper( )’ function we can convert that zeroth indexed position element into uppercase and is stored in variable ‘a’. Print ‘a’. By using ‘for’ loop we perform iterations on the remaining elements in the string. When the base condition ‘if (str[i]==’ ‘)’ evaluates to true and the statement ‘str[i + 1].upper( )’ increments the index position of that string and converts them into uppercase with in-built function ‘upper( )’. This continues until the base condition fails. Now, we call the function definition ‘Initials(str)’ and finally it print every character after space in capital letter.

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest