How to Extract Initials from a Name in Python

Python Basics: Extracting Initials from a Name – A Step-by-Step Guide for Beginners As a Python enthusiast, I love sharing simple code snippets that can help beginners understand the basics of string manipulation. Today, let’s break down a short Python script that extracts the initials from a full name and prints them in uppercase. This is perfect for tasks like generating acronyms or user badges. Here’s the code using the name “Kannan Srinivasan”: name = "Kannan Srinivasan" initials = "".join([word[0].upper() for word in name.split()]) print(initials) When you run this, it outputs: KS Now, let’s explain it step by step for beginners—no prior experience needed! I’ll walk you through what each part does: 1 Assign the name to a variable:
name = "Kannan Srinivasan"
This creates a string variable called name and stores the full name in it. Strings are just text enclosed in quotes. Here, the name has two words separated by a space. 2 Split the name into words:
Inside the code: name.split()
The .split() method breaks the string into a list of words using spaces as the separator. For “Kannan Srinivasan”, this gives: ['Kannan', 'Srinivasan'].
(A list is like a collection of items, e.g., [item1, item2].) 3 Extract the first letter of each word and make it uppercase:
Inside the list comprehension: [word[0].upper() for word in name.split()]
This is a “list comprehension”—a compact way to create a new list by looping over the words. ◦ for word in name.split(): Loops through each word in the list from step 2. ◦ word[0]: Gets the first character of the word (index 0, since Python counts from 0). ◦ .upper(): Converts that character to uppercase (e.g., ‘k’ becomes ‘K’).
Result: For our name, this creates ['K', 'S']. 4 Join the initials into a single string:
"".join(...)
The .join() method combines the list of initials into one string. The "" means no spaces or separators between them, so ['K', 'S'] becomes "KS". This is assigned to the variable initials. 5 Print the result:
print(initials)
This simply outputs the initials to the console: “KS”. In a real app, you could use this for displaying on a profile or generating an avatar. This snippet is concise thanks to Python’s list comprehensions, but it’s a great intro to strings, lists, and methods. Try it yourself in a Python editor like VS Code or an online REPL—change the name and see what happens! #Python #CodingForBeginners #TechTips

To view or add a comment, sign in

Explore content categories