Open In App

Python | Print the initials of a name with last name in full

Last Updated : 23 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. 

Examples:

Input : geeks for geeks
Output : G.F.Geeks

Input : mohandas karamchand gandhi
Output : M.K.Gandhi 

A naive approach of this will be to iterate for spaces and print the next letter after every space except the last space. At last space we have to take all the characters after the last space in a simple approach. Using Python in inbuilt functions we can split the words into a list, then traverse till the second last word and print the first character in capitals using upper() function in python and then add the last word using title() function in Python which automatically converts the first alphabet to capital. 

Implementation:

Python3




# python program to print initials of a name
def name(s):
 
    # split the string into a list
    l = s.split()
    new = ""
 
    # traverse in the list
    for i in range(len(l)-1):
        s = l[i]
         
        # adds the capital first character
        new += (s[0].upper()+'.')
         
    # l[-1] gives last item of list l. We
    # use title to print first character in
    # capital.
    new += l[-1].title()
     
    return new
     
# Driver code           
s ="mohandas karamchand gandhi"
print(name(s))       


Output

M.K.Gandhi

The time complexity of this algorithm is O(n) where n is the number of words in the string. This is because the algorithm only iterates through the string once.

The space complexity of this algorithm is O(n) because a new string is created and all the words in the string are stored in a list.

Using regular expressions:

Algorithm:

  1. Import the re module for using regular expressions.
  2. Define a function name which takes a string as input.
  3. Use the re.findall() function to extract the first letter of each word in the string s. The regular expression ‘\b\w’ matches the first letter of each word. The ‘\b’ specifies a word boundary and ‘\w’ matches any alphanumeric character.
  4. Use the re.findall() function again to extract the last word in the string s. The regular expression ‘\b\w+$’ matches the last word in the string. The ‘$’ specifies the end of the string.
  5. Combine the initials and last name with dots using the join() function. The join() function concatenates the elements of a list into a string using a specified delimiter.
  6. Convert the initials to uppercase and last name to title case (i.e. capitalize the first letter of each word).
  7. Return the result.

Python3




import re
 
def name(s):
  # Use regular expression to extract the first letter of each word
  initials = re.findall(r'\b\w', s)
   
  # Use regular expression to extract the last word
  last_name = s.split()[-1]
  # Combine the initials and last name with dots
  result = '.'.join(initials[:-1]).upper() + '.' + last_name.title()
 
  return result
 
#Driver code
s = "mohandas karamchand gandhi"
print(name(s))


Output

M.K.Gandhi

Time complexity: The time complexity of the regular expression approach is O(n), where n is the length of the input string s. This is because the re.findall() function iterates over the string s once to extract the required characters.

Space complexity: The space complexity of the regular expression approach is O(n), where n is the length of the input string s. This is because the re.findall() function creates a list to store the extracted characters, and the result string also takes up space proportional to the length of s.



Similar Reads

Program to print the initials of a name with the surname
Given a full name in the form of a string, the task is to print the initials of a name, in short, and the surname in full. Examples: Input: Devashish Kumar GuptaOutput: D. K. GuptaInput: Ishita BhuiyaOutput: I. BhuiyaApproach: The basic approach is to extract words one by one and then print the first letter of the word, followed by a dot(.). For th
9 min read
Program to find the initials of a name.
Given a string name, we have to find the initials of the name Examples: Input : prabhat kumar singh Output : P K S We take the first letter of all words and print in capital letter. Input : Jude Law Output : J L Input : abhishek kumar singh Output : A K SPrint first character in capital. Traverse rest of the string and print every character after s
6 min read
Python - Render Initials as Dictionary Key
Given List of Strings, convert to dictionary with Key as initial value of values. Won't work in cases having words with similar initials. Input : test_list = ["geeksforgeeks", "is", "best"] Output : {'g': 'geeksforgeeks', 'i': 'is', 'b': 'best'} Explanation : Keys constructed from initial character. Input : test_list = ["geeksforgeeks", "best"] Out
5 min read
Python Program to Sort A List Of Names By Last Name
Given a list of names, the task is to write a Python program to sort the list of names by their last name. Examples: Input: ['John Wick', 'Jason Voorhees'] Output: ['Jason Voorhees', 'John Wick'] Explanation: V in Voorhees of Jason Voorhees is less than W in Wick of John Wick. Input: ['Freddy Krueger', 'Keyser Söze','Mohinder Singh Pandher'] Output
3 min read
Last digit of a number raised to last digit of N factorial
Given two number X and N, the task is to find the last digit of X raised to last digit of N factorial, i.e. [Tex]X^{\left ( N! \right )mod 10} [/Tex].Examples: Input: X = 5, N = 2 Output: 5 Explanation: Since, 2! mod 10 = 2 therefore 52 = 25 and the last digit of 25 is 5.Input: X = 10, N = 4 Output: 0 Explanation: Since, 4! mod 10 = 24 mod 10 = 4 t
15 min read
Last seen array element (last appearance is earliest)
Given an array that might contain duplicates, find the element whose last appearance is latest. Examples: Input : arr[] = {10, 30, 20, 10, 20} Output : 30 Explanation: Below are indexes of last appearances of all elements (0 based indexes) 10 last occurs at index 3 30 last occurs at index 1 20 last occurs at index 2 The element whose last appearanc
5 min read
Python IMDbPY – Getting Person name from searched name
In this article we will see how we can get the person name from the searched list of name, we use search_name method to find all the related names.search_name method returns list and each element of list work as a dictionary i.e. they can be queried by giving the key of the data, here key will be name. Syntax : names[0]['name']Here names is the lis
2 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
Python - Print the last word in a sentence
Given a string, the task is to write a Python program to print the last word in that string. Examples: Input: sky is blue in color Output: color Explanation: color is last word in the sentence. Input: Learn algorithms at geeksforgeeks Output: geeksforgeeks Explanation: geeksforgeeks is last word in the sentence. Approach #1: Using For loop + String
5 min read
Check if a string is the typed name of the given name
Given a name and a typed-name of a person. Sometimes, when typing a vowel [aeiou], the key might get long pressed, and the character will be typed 1 or more times. The task is to examine the typed-name and tell if it is possible that typed name was of person's name, with some characters (possibly none) being long pressed. Return 'True' if it is, el
8 min read
three90RightbarBannerImg