How to Get the First Character of a String

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``

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``

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']``

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

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``````

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!