# Understanding Strings: The Building Blocks of Text in Python

Welcome to **Episode 7** of *The Medical Coder’s Path*!

In Episode 6, we introduced **Python data types** and provided a general overview of collections like lists, tuples, and dictionaries. Now, in Episode 7, we’ll begin exploring **each data type one by one**, starting with **Strings**.

### 🎯 Objective

By the end of this episode, learners will understand:

* What a **string** is in Python.
    
* How to create and store strings.
    
* The `len()` Function in Python
    
* Common **string operations** (concatenation, indexing, and slicing).
    

Let’s get started!

---

## What a **string** is in Python

In Python, a **string** is a sequence of characters, which can include letters, numbers, or symbols, enclosed in either **single quotes** (`'...'`) or **double quotes** (`"..."`). These quotes are known as delimiters. A **delimiter** is a character that indicates where a string begins and ends in Python.

📌 Example (healthcare context):

```python
patient_name = "Ahmed Ali"
diagnosis = "Hypertension"
hospital_id = "CH12345"
hospital = 'City Hospital'
```

Python can tell us what kind of data we’re dealing with by using the `type()` function.

Example:

```python
patient_name = "Ahmed Ali"
print(type(patient_name))
```

Output:

```javascript
<class 'str'>
```

This shows that the variable `patient_name` is of the type **string** (`str`).

### Strings vs. String Literals

* **String**: In Python, a string is a data type used to represent text. When we call something a *string*, it means the stored value is text.  
    **String literal**: This refers to the exact characters you write in your code to create a string. For example, `"Mohamed Omer"` is a **string literal**, the quotes and text you type. When stored in a variable, like `patient_name = "Mohamed Omer"`, the value of `patient_name` is a **string**.
    

👉 In short:

```javascript
String Literal → "Mohamed Omer"  (what you write in code with quotes)
String         → Mohamed Omer    (the actual stored text)
```

---

## The `len()` Function in Python

In Python, the `len()` function is used to find the **length** of a string, which is the total number of characters it contains, including spaces and symbols.

This is very useful in healthcare settings, for example, when checking if a patient ID or medical record number has the correct length.

### 🩺 Example 1: Simple String

```python
patient_name = "Ahmed Ali"
print(len(patient_name))
```

**Output:**

```javascript
9
```

👉 The string `"Ahmed Ali"` has **9 characters** (including the space between Ahmed and Ali).

### 🩺 Example 2: Patient ID

```python
patient_id = "MRN12345"
print(len(patient_id))
```

**Output:**

```javascript
8
```

👉 The patient ID has **8 characters**, which can be checked to ensure it matches the required format.

### 🩺 Example 3: Empty String

```javascript
note = ""
print(len(note))
```

**Output:**

```javascript
0
```

👉 An empty string has a length of **0**.

✅ **Key Takeaway:**

* `len()` counts every character, including spaces, numbers, and symbols.
    
* It helps you **validate input** (e.g., ensuring a password, patient ID, or report isn’t too short or too long).
    

---

## Multiline Strings in Python

Sometimes, a single line of text is not enough. In healthcare or medical informatics, you may want to store **long notes**, **discharge summaries**, or **patient history** that spread across multiple lines.

Python allows us to create **multiline strings** using **triple quotes** (`"""` or `'''`).

### 🩺 Example 1: Patient Note

```python
patient_note = """Patient complains of headache.
Blood pressure measured at 140/90.
Advised to reduce salt intake and follow up in 2 weeks."""
print(patient_note)
```

**Output:**

```javascript
Patient complains of headache.
Blood pressure measured at 140/90.
Advised to reduce salt intake and follow up in 2 weeks.
```

👉 Notice how the text keeps its **format across multiple lines**.

### 🩺 Example 2: Medical Report (with triple single quotes)

```python
medical_report = '''Lab results:
- Hemoglobin: 13.5 g/dL
- Glucose: 95 mg/dL
- Cholesterol: Normal
'''
print(medical_report)
```

**Output:**

```javascript
Lab results:
- Hemoglobin: 13.5 g/dL
- Glucose: 95 mg/dL
- Cholesterol: Normal
```

### ✅ Key Notes on Multiline Strings

* They are defined with **triple quotes** (`"""` or `'''`).
    
* Useful for **storing paragraphs, reports, or formatted text**.
    

---

## String Operations

### 1️⃣ **Concatenation (Joining strings together)**

Concatenation means **combining two or more strings into one**. This is very useful in healthcare when you want to join patient information, like their name and ID, into a single message, using the `+` operator.

single message.

```python
first_name = "Ahmed"
last_name = "Ali"
full_name = first_name + " " + last_name # The purpose of the double quotes here is to create a space between the two names. 
print(full_name)
```

**Output:**

```javascript
Ahmed Ali
```

### 2️⃣ Repetition (Repeating a string)

Repetition allows you to **repeat a string multiple times** using the `*` operator. This can be helpful, for example, when creating separators in reports or repeating a symbol.

```python
separator = "-" * 30
print(separator)
```

**Output:**

```javascript
------------------------------
```

### 3️⃣ Indexing (Accessing a single character)

When you write a string in Python, Python stores it in memory as a sequence of characters. To help us find or work with specific characters, Python gives each character a **numbered position**, which we call an **index**.

Think of a string as a row of numbered lockers, where each locker holds one character.

* ### Indexing from Left to Right (Positive Indexing)
    
    In Python, when you count **from the left side**, indexing starts at **0** (not 1).
    
    For example:
    

```python
word = "HELLO"
```

Here’s how Python sees it:

| Character | H | E | L | L | O |
| --- | --- | --- | --- | --- | --- |
| Index | 0 | 1 | 2 | 3 | 4 |

👉 That means:

* `word[0]` → `"H"`
    
* `word[1]` → `"E"`
    
* `word[4]` → `"O"`
    

### Indexing from Right to Left (Negative Indexing)

Python also allows us to count **from the right side**. When we count backwards, the index starts at **\-1**.

Using the same example:

```python
word = "HELLO"
```

| Character | H | E | L | L | O |
| --- | --- | --- | --- | --- | --- |
| Index | \-5 | \-4 | \-3 | \-2 | \-1 |

👉 That means:

* `word[-1]` → `"O"` (last character)
    
* `word[-2]` → `"L"` (second from the right)
    
* `word[-5]` → `"H"` (first character, same as index 0)
    

```python
patient_id = "MRN12345"
print(patient_id[0])  # First character
print(patient_id[-1]) # Last character
```

**Output:**

```javascript
M
5
```

### 4️⃣ Slicing (Extracting part of a string)

**Slicing** means cutting out a **substring** (a smaller piece of a string) by telling Python where to start and where to stop.

The basic syntax is:

```python
string[start:stop]
```

* **start** → the index where the slice begins (included).
    
* **stop** → the index where the slice ends (excluded).
    

```python
word = "HOSPITAL"

print(word[0:4])   # "HOSP"
print(word[2:7])   # "SPITA"
```

👉 Notice that the slice includes the character at the start index, but stops right before the stop index.

**Output:**

```python
HOSP
SPITA
```

Sometimes you don’t always have to write both numbers.

* If you leave out **start**, Python begins at the beginning.
    
* If you leave out **stop**, Python goes all the way to the end.
    

```python
print(word[:4])   # "HOSP"   (from start to index 3)
print(word[3:])   # "PITAL"  (from index 3 to end)
print(word[:])    # "HOSPITAL" (entire string)
```

You can also slice from the right using **negative indexes**.

```python
print(word[-4:])   # "ITAL"  (last 4 letters)
print(word[:-3])   # "HOSPI" (everything except last 3)
```

There’s an optional **step** value:

```python
string[start:stop:step]
```

* **step** tells Python how many characters to skip.
    

```python
print(word[0:7:2])   # "HSPL" (every 2nd character)
print(word[::-1])    # "LATIPSOH" (reverses the string)
```

Slicing is like cutting out a piece of a cake; it always includes the **start** index but stops right before the **stop** index. You can use positive or negative indices, and you can also add a **step** to skip characters or reverse a string.

### 5️⃣ Membership (Checking if a word exists in a string)

You can use the keywords `in` or `not in` to check if a substring exists inside a string.

```python
note = "Patient has diabetes"
print("diabetes" in note)     # True
print("cancer" not in note)   # True
```

**Output:**

```javascript
True
True
```

These are the **basic string operations**. Later, we can also explore **string methods** (like `.lower()`, `.upper()`, `.replace()`, etc.) which make working with strings even more powerful.

---

Let’s wrap up Episode 7 with a **hands-on exercise!**

## 📝 Practice Exercise: Strings in Action

You are given this string:

```javascript
patient_name = "Samar Ali"
```

### Part 1: Indexing

1. Print the **first character** of the name.
    
2. Print the **last character** of the name.
    

### Part 2: Slicing

3. Extract `"Samar"` from the string.
    
4. Extract `"Ali"` from the string.
    
5. Reverse the entire string.
    
6. Get every **second letter** in `"Samar"`.
    

### Part 3: String Operations

7. Concatenate `" Samar Ali"` with the string `" is a patient"`.
    
8. Repeat the string `"ID-"` **3 times**.
    
9. Find the **length of the string** using `len()`
    

After you finish, **send your answers to my email saja@sajamedtech.com for feedback**.

---

## What’s Next?

In the next episode, we’ll explore **string methods** in Python that allow us to **transform, clean, and analyze text data** more effectively.

See You Later!
