How to Get the First Character of a String

4.9/5 - (8 votes)

Problem Formulation and Solution Overview

This article will show different ways to extract the first character of a Python string.

To make it more interesting, we have the following scenario:

The Government has asked Rivers Clothing to complete forms for each employee. These forms require the first character of the employee’s first name and their full last name. They need your help.

Example

J. Hamilton

💬 Question: How would we write code to extract this data?

We can accomplish this task by one of the following options:


Method 1: Use slicing

This method uses slicing to extract the first character from an employee’s first name and their full last name.

Extract First Character of the First Name String

This example extracts the first character from an employee’s first name.

emp_name =  "Micah Jamison"
fname_chr = emp_name[0]
print(fname_chr)

The first line in the above code snippet declares and saves an employee’s full name to emp_name.

The following line extracts the first character of emp_name using slicing and saves the results to fname_chr.

The next line outputs the contents of fname_chr to the terminal.

M

Extract First Character of First Name String & Full Last Name String

emp_name =  "Micah Jamison".split()
print(f'{emp_name[0][0]}. {emp_name[1]}')

The first line in the above code snippet declares an employee’s name. Then, split() is applied to this string. This function, by default, splits a string on the space character (unless otherwise specified). The results save to emp_name as a List.

['Micah', 'Jamison']

The following line extracts the first character of the first name and the full last name using slicing and outputs this to the terminal.

M. Jamison
The Ultimate Guide to Slicing in Python

Method 2: Use slicing, encode() and decode()

This method uses slicing and the encode() and decode() functions to extract the first character from an employee’s first name and their full last name. This code also accounts for characters that fall outside the realm and may not resolve properly, for example, a French accent.

Extract First Character of the First Name String

emp_name = "Éloise Pierre"
print(emp_name.encode(encoding='utf-8').decode()[0])

The first line in the above code snippet declares and saves the employee’s name to emp_name.

The following line applies the encode() and decode() functions to emp_name. This converts the characters into a readable format. Then slicing is applied to extract the first character from this string.

The results are output to the terminal.

É

Extract First Character of First Name String & Full Last Name String

emp_name = "Éloise Pierre"
print(f"{emp_name.encode(encoding='utf-8').decode().split()[0][0]}. {emp_name.encode(encoding='utf-8').decode().split()[1]}")
É. Pierre
Python String Methods [Ultimate Guide]

Method 3: Use __getitem__

This method uses __getitem__() to extract the first character from the employee’s first name

Extract First Character of the First Name String

emp_name = "Éloise Gregoire"
print(emp_name.__getitem__(0))

The __getitem__() function is referred to as the Magic Method and is used to extract an item from an invoked instance. In this case, emp_name.

In this code snippet, __getitem__() is applied to emp_name and passed an integer as the item/slice to extract. The results are then output to the terminal.

É

Method 4: Use List Comprehension

This method uses List Comprehension to extract the first character of each employee in the List.

Extract First Character of the First Name String

emps = ['Micah Jamison', 'Eloise Jax', 'Ben Hamilton']
chrs = [x[0] for x in emps]
print(chrs)

The first line in the above code snippet creates a list of Rivers Clothing employees and saves the result to emps.

The following line uses List Comprehension to extract the first character from each List item. The results save to chrs and are output to the terminal.

['M', 'E', 'B']
Python One-Liner Trick 9 - Nested List Comprehension

Method 5: Use map() and zip()

This method uses map() and zip() to extract the first character from an employee’s first name and their full last name.

To run this code error-free, ensure the Pandas library is installed.

Extract First Character of First Name String & Full Last Name String

 import pandas as pd

df = pd.read_csv('emps.csv', names=['fname', 'lname'])
fname = map(str, (df.fname.tolist())[1:])
lname = map(str, (df.lname.tolist())[1:])

for first, last in zip(fname, lname):
        print(f'{first[0]}. {last}')

The first line in the above code snippet imports the Pandas library. This allows access to and manipulation of DataFrames.

The following line reads the emps.csv file into the DataFrame df.

The next two (2) lines create objects of the fname and lname columns (excluding the header names). If output to the terminal, they would appear similar to below:

<map object at 0x00000221D8068820>
<map object at 0x00000221D8068B50>

A for loop is then instantiated, and the two (2) objects created earlier are zipped and combined into a single zip object. This allows the code access to both the fname and lname columns.

Each iteration outputs the first initial and full last name to the terminal.

M. Jamison
É. Pierre
B. Jones
Ä. Schmidt
S. Price
Zip & Unzip: How Does It Work in Python?

Summary

This article has provided five (5) ways to extract the first character and/or the full last name from a string to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd