Open In App

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

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with strings, we might need to format a full name such that the initials of the first and middle names are displayed, while the last name is shown in full. Let’s discuss some methods to achieve this in Python.

Using split() and a loop

split() and a loop method splits the name into words and processes the initials for all but the last word, which is then appended as it is.

Python
# Input name
n = "Zoe Kristen Davis"

# Split the name into parts
parts = n.split()

# Process the initials and add the last name
res = " ".join([part[0] + "." for part in parts[:-1]]) + " " + parts[-1]
print(res)  

Output
Z. K. Davis

Explanation:

  • Splitting the name into a list of words using split().
  • Using a for loop to get the first character of each word, adding a period after it.
  • Joining the initials and append the last name as-is.

Let’s explore some more methods and see how we can print the initials of a name with last name in full.

Using list comprehension

This method uses a list comprehension for concise processing of initials and directly appends the last name.

Python
n = "Zoe Kristen Davis"

# Split and process the name
res = " ".join([word[0] + "." for word in n.split()[:-1]]) + " " + n.split()[-1]
print(res)  

Output
J. M. Doe

Explanation:

  • Here, we split the name using split().
  • Using a list comprehension to process initials for all but the last word.
  • Appending the last word as it is.

Using enumerate() in a loop

This method uses enumerate() to process each part of the name, adding initials for all words except the last.

Python
n = "Zoe Kristen Davis"

# Initialize result
res = ""

# Loop through each part of the name
for i, part in enumerate(n.split()):
    if i == len(n.split()) - 1:
        res += part  # Append the last name
    else:
        res += part[0] + ". "  # Append initials
print(res)  

Output
Z. K. Davis

Explanation:

  • Using enumerate() to loop through the parts of the name.
  • Checking if the current part is the last name; if so, appending it directly.
  • Otherwise, we append the first character with a period.

Using regular expressions

This method uses a regular expression to match each word and extract the initials and last name.

Python
import re

# Input name
n = "Zoe Kristen Davis"

# Use regex to extract initials and last name
parts = re.findall(r'\b\w+', n)
res = " ".join([word[0] + "." for word in parts[:-1]]) + " " + parts[-1]
print(res)  

Output
Z. K. Davis

Explanation:

  • Using re.findall() to extract words from the string.
  • Processing the initials for all but the last word using a loop or list comprehension.
  • Appending the last word directly.


Next Article

Similar Reads