# 🧵 Python Part 2: Strings and User Input in Python

### 1️⃣ What is a String?

* Creating strings with single or double quotes
    
* Python treats all input from `input()` as strings
    

---

### 2️⃣ Python String Formatting Methods

* `%` Formatting (C-style)
    
    * Format specifiers: `%s`, `%d`, `%f`
        
* `.format()` method
    
    * Positional placeholders
        
* `f-strings` (Modern and recommended)
    
* ✅ Summary Table: Python String Formatting Styles
    

---

### 3️⃣ String Concatenation in Python

* Definition and basic example
    
* Mixing strings with other data types
    
* Comma `,` vs plus `+` in print
    
* Accidental line breaks and multiline concatenation
    
* Alternatives: `f-strings`, `.format()`
    
* 🔚 Summary Table: Concatenation Methods
    

---

### 4️⃣ String Repetition in Python

* What is repetition (`*`)
    
* Pitfalls to avoid (`TypeError`)
    
* Print tricks with `\n` and emojis
    

---

### 5️⃣ Measuring String Length with `len()`

* What is `len()`
    
* Examples with letters, spaces, emojis
    
* Real-world use cases
    
* Common mistakes and fixes
    

---

### 6️⃣ String Indexing in Python

* Zero-based indexing
    
* Negative indexing
    
* Index reference table
    
* IndexError example
    
* Indexing in loops
    
* Strings are immutable (read-only)
    

---

### 7️⃣ String Slicing in Python

* Basic slicing: `[start:stop]`
    
* Why stop index is excluded
    
* Negative slicing
    
* Slicing with step: `[start:stop:step]`
    

---

### 8️⃣ Real-World Use Cases for String Methods

* `.split()`, `.join()`, `.strip()`, `.replace()`
    
* `.upper()`, `.lower()`, `.capitalize()`, `.title()`
    
* `.startswith()`, `.endswith()`, `.find()`, `.count()`
    
* `.isdigit()`, `.isalpha()`
    

---

### 9️⃣ User Input in Python

* How `input()` works
    
* 🔁 Type conversion (`int()`, `float()`, `str()`)
    
* ✨ Cleaning input: `.strip()`, `.capitalize()`
    
* ✅ Validation:
    
    * `.isdigit()` for numbers
        
    * `.isalpha()` for letters
        
* ✅ Real-world input with `.split()`
    

---

### 🔟 Escape Characters in Strings

* `\n` – New line
    
* `\t` – Tab
    
* `\\` – Backslash
    
* `\'` – Single quote
    
* `\"` – Double quote
    

---

### 1️⃣1️⃣ Multi-line Strings in Python (`"""..."""`)

* Triple double or single quotes
    
* Preserving line breaks
    
* Practical example with message formatting
    

### 1️⃣ What is a String?

A string is text in Python. You create it using quotes:

You can use single or double quotes, but they must match.

```python
text1 = "Hello"
text2 = 'World'
print(text1, text2)
```

**Output:**

```python
Hello World
```

Also, when you use `input()` in Python, it always returns a string, even if the user types a number.

---

### 2️⃣ Python String Formatting Methods

There are 3 main ways to insert variables into strings:

| **Method** | **Introduced In** | **Description** |
| --- | --- | --- |
| `%` operator | Python 2.x | Oldest method (C-style formatting) |
| `.format()` | Python 2.6+ | More readable and flexible |
| `f-strings` | Python 3.6+ | Most modern, readable, and fastest |

#### 1\. `%` Formatting (C-style)

```python
name = "Lorenzo"
age = 25
print("My name is %s and I am %d years old." % (name, age))
```

**Output:**

```python
My name is Lorenzo and I am 25 years old.
```

### 🧠 Format Specifiers for `%` Formatting

| **Specifier** | **Meaning** |
| --- | --- |
| `%s` | String |
| `%d` | Integer (decimal) |
| `%f` | Float (decimal) |

#### 2\. `.format()` Method

```python
print("My name is {} and I am {} years old.".format(name, age))
```

**Output:**

```python
My name is Lorenzo and I am 25 years old.
```

```python
print("My name is {0} and I'm {1}. {0} is learning Python.".format(name, age))
```

**Output:**

```python
My name is Lorenzo and I'm 25. Lorenzo is learning Python.
```

#### 3\. `f-Strings` (Modern and Best)

```python
print(f"My name is {name} and I am {age} years old.")
```

**Output:**

```python
My name is Lorenzo and I am 25 years old.
```

```python
print(f"Next year, I’ll be {age + 1}")
```

**Output:**

```python
Next year, I’ll be 26
```

### ✅ Summary Table: Python String Formatting Styles

| **Style** | **Example** | **Use When...** |
| --- | --- | --- |
| `%` | "Hello %s" % name | Reading or maintaining older code |
| `.format()` | "Hello {}".format(name) | You need reusable or numbered placeholders |
| `f-strings` | f"Hello {name}" | You're using Python 3.6 or newer (recommended) |

---

## 🧵 Important Python String Methods

| **Method** | **Example** | **What It Does** |
| --- | --- | --- |
| `.split()` | "a b c".split() | Splits a string into a list |
| `.join()` | " ".join(\["a", "b", "c"\]) | Joins a list into a single string |
| `.strip()` | " hello ".strip() | Removes leading/trailing whitespace |
| `.replace()` | "hi".replace("h", "b") | Replaces part of a string |
| `.upper()` | "abc".upper() | Converts to uppercase |
| `.lower()` | "ABC".lower() | Converts to lowercase |
| `.capitalize()` | "hello".capitalize() | Capitalizes the first letter only |
| `.title()` | "hello world".title() | Capitalizes the first letter of every word |
| `.startswith()` | "python".startswith("py") | Checks if string starts with something (True/False) |
| `.endswith()` | "data.csv".endswith(".csv") | Checks if string ends with something (True/False) |
| `.find()` | "hello".find("l") | Returns the index of first match or -1 if not found |
| `.count()` | "banana".count("a") | Counts how many times a character appears |
| `.isdigit()` | "123".isdigit() | Checks if the string contains only digits |
| `.isalpha()` | "abc".isalpha() | Checks if the string contains only letters |

---

## 🔤 String Operations in Python

| **Operation** | **Example** | **Result** |
| --- | --- | --- |
| Concatenation | "Hello" + " World" | 'Hello World' |
| Repetition | "Hi" \* 3 | 'HiHiHi' |
| Length | len("Python") | 6 |
| Indexing | "Python"\[0\] | 'P' |
| Slicing | "Python"\[1:4\] | 'yth' |
| Uppercase | "hello".upper() | 'HELLO' |
| Lowercase | "HELLO".lower() | 'hello' |
| Replace | "Hello".replace("l", "z") | 'Hezzo' |

---

### 3️⃣ String Concatenation in Python

### 📌 Definition:

Joining two or more strings together using the `+` operator.

### ✅ Example:

```python
greeting = "Hello"
name = "Lorenzo"
message = greeting + " " + name
print(message)  # Output: Hello Lorenzo
```

**Output:**

```python
Hello Lorenzo
```

### ❌ Mixing Strings with Other Data Types

You must convert non-strings before concatenating:

```python
age = 25
# print("Age: " + age)     # ❌ Error!
print("Age: " + str(age))  # ✔️ Correct
```

**Output:**

```python
Age: 25
```

### 🥵 Confusing Commas with `+` in `print()`

* `,` adds spaces automatically
    
* `+` does not
    

```python
name = "Lorenzo"
print("Hello", name)        # ✔️ Output: Hello Lorenzo
print("Hello" + name)       # ✔️ Output: HelloLorenzo
print("Hello" + " " + name) # ✔️ Output: Hello Lorenzo
```

**Output:**

```python
Hello Lorenzo
HelloLorenzo
Hello Lorenzo
```

### 🪓 Accidental Line Breaks or Extra Spaces

#### Using backslash (`\`) to continue line:

```python
message = "Hello " + \
          "there!"
print(message)
```

**Output:**

```python
Hello there!
```

#### Invalid example (line break without `\`):

```python
'''
bad_message = "Hello " 
+ "there!"   # ❌ SyntaxError
'''
```

#### Better: use parentheses:

```python
message1 = ("This is a " 
            "clean and readable "
            "way to concatenate.")
print(message1)
```

**Output:**

```python
This is a clean and readable way to concatenate.
```

---

### ✅ Better Alternatives: `f-Strings` and `.format()`

```python
name = "Lorenzo"
age = 25
print("Name: " + name + ", Age: " + str(age))
```

**Output:**

```python
Name: Lorenzo, Age: 25
```

#### Using f-strings:

```python
print(f"Name: {name}, Age: {age}")
```

**Output:**

```python
Name: Lorenzo, Age: 25
```

#### Using `.format()`:

```python
print("Name: {}, Age: {}".format(name, age))
```

**Output:**

```python
Name: Lorenzo, Age: 25
```

---

### 🔚 Summary Table

#### 🧹 String Concatenation Methods in Python

| **Method** | **Description** | **Good For** |
| --- | --- | --- |
| `+` operator | Simple joins, but limited to strings | Small programs |
| `join()` | Efficient for joining lists of strings | Loops, file content |
| `f-strings` | Most readable and flexible | All modern Python (3.6+) |
| `format()` | Useful for formatting numbers/strings | When f-strings not used |

---

### 4️⃣ String Repetition in Python

In Python, you can repeat a string multiple times using the `*` operator:

**Syntax:**

```python
string * number
```

### ✅ Examples:

```python
print("Hi" * 3)        # Output: HiHiHi
print("=-" * 5)        # Output: =-=-=-=-=-
print("Hello\n" * 2)   # Output: Hello\nHello
```

**Output:**

```python
HiHiHi
=-=-=-=-=-
Hello
Hello
```

### 🚫 Pitfalls to Avoid:

```python
# "Hello" * "3"   ❌ TypeError
# "Hello" * 2.5   ❌ TypeError
```

You can only multiply a string by an **integer**, not a string or float.

### 🎯 Works with print() Tricks

```python
print("\n" * 3)      # Adds 3 blank lines
print("🚀" * 5)      # Repeats emoji 5 times
```

**Output:**

```python



🚀🚀🚀🚀🚀
```

---

### 5️⃣ Measuring String Length with `len()`

The `len()` function returns the number of characters in a string — including letters, spaces, and emojis.

### ✅ Examples:

```python
print(len("Python"))          # 6
print(len("Hello World"))     # 11
print(len("12345"))           # 5
print(len("") )               # 0 (empty string)
print(len("🚀🔥"))            # 2 (each emoji counts as one)
```

**Output:**

```python
6
11
5
0
2
```

### 🧠 Useful in Real Life:

* Input validation (e.g., max 10 characters)
    
* Password length checking
    
* Looping through characters
    
* Checking if a string is empty:
    

```python
if len(text) == 0:
    print("Empty!")
```

### ⚠️ Common Mistakes to Avoid:

| Mistake | Problem | Fix |
| --- | --- | --- |
| `len["Hello"]` | ❌ TypeError (wrong syntax) | ✅ Use parentheses: `len("Hello")` |
| Using `len()` on None | ❌ TypeError | ✅ Check with `if string:` |
| Counting words | ❌ Counts characters | ✅ Use `.split()` then `len()` |

### ✅ Counting Words in a Sentence:

```python
sentence = "This is Python"
print(len(sentence.split()))  # Output: 3 words
```

**Output:**

```python
3
```

### ✅ Summary

* `len()` counts characters, not words (unless used with `.split()`).
    
* Works with **strings**, **lists**, **tuples**, and more.
    

---

### 6️⃣ String Indexing in Python

Indexing means accessing individual characters in a string using their **position** (index).

Python uses **zero-based indexing**:

* Index `0` is the first character
    
* Index `1` is the second, and so on
    

### ✅ Examples:

```python
text = "Python"
print(text[0])  # P
print(text[1])  # y
print(text[5])  # n
```

**Output:**

```python
P
y
n
```

### 🧭 Negative Indexing

Python also supports **negative indexing** to count from the end:

```python
text = "Python"
print(text[-1])  # n
print(text[-2])  # o
print(text[-6])  # P
```

**Output:**

```python
n
o
P
```

### 🔢 String Index Reference Table

| Character | P | y | t | h | o | n |
| --- | --- | --- | --- | --- | --- | --- |
| Index (Positive) | 0 | 1 | 2 | 3 | 4 | 5 |
| Index (Negative) | \-6 | \-5 | \-4 | \-3 | \-2 | \-1 |

### ⚠️ IndexError Example

```python
text = "Python"
print(text[10])  # ❌ IndexError: string index out of range
```

> Indexing only works on **sequences** like: `str`, `list`, `tuple`, `range`

### ✅ Indexing in Loops

```python
word = "Test"
for i in range(len(word)):
    print(word[i])
```

**Output:**

```python
T
e
s
t
```

> 🧠 Note: Strings are **immutable** in Python — you cannot change a character using indexing:

```python
word = "Hi"
word[0] = "B"  # ❌ TypeError
```

---

---

### 7️⃣ String Slicing in Python

Slicing lets you extract a portion (or "slice") of a string by specifying:

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

* `start`: index where the slice begins (**inclusive**)
    
* `stop`: index where the slice ends (**exclusive**)
    
* If you skip one, Python uses defaults
    

### ✅ Examples:

```python
text = "Python"
print(text[1:4])   # 'yth' → characters at index 1, 2, 3
print(text[:3])    # 'Pyt' → from beginning to index 2
print(text[3:])    # 'hon' → from index 3 to end
print(text[:])     # 'Python' → entire string
```

**Output:**

```python
yth
Pyt
hon
Python
```

### 🤔 Why Does Python Include the Start But Exclude the End?

```python
text = "Python"
print(text[1:4])  # 'yth'
```

* Includes index 1 → 'y'
    
* Includes index 2 → 't'
    
* Includes index 3 → 'h'
    
* Excludes index 4 → 'o' is **not included**
    

### 🧭 Negative Indexing Works Too:

```python
text = "Python"
print(text[-3:])   # 'hon'
print(text[:-2])   # 'Pyth'
```

**Output:**

```python
hon
Pyth
```

### 🧠 General Syntax: `string[start:stop:step]`

* `start` → where to begin (inclusive)
    
* `stop` → where to end (exclusive)
    
* `step` → how many steps to move (positive or negative)
    

### ✅ Step-Based Slicing Examples:

```python
text = "Python"

print(text[::-1])   # 'nohtyP' → Reversed string
print(text[::2])    # 'Pto'    → Every 2nd character from start
print(text[1:5:2])  # 'yh'     → From index 1 to 4, every 2nd char
```

**Output:**

```python
nohtyP
Pto
yh
```

> 🔁 Use slicing often when you need substrings, reversals, or selective skipping.

### 8️⃣ Real-World Use Cases for String Methods

---

---

| **Method** | **Example** | **Result** | **Use Case** |
| --- | --- | --- | --- |
| `.split()` | `"John,Doe,30".split(",")` | `['John', 'Doe', '30']` | Parsing CSV-formatted user data from a file or API |
| `.join()` | `", ".join(["apple", "banana"])` | `'apple, banana'` | Displaying a product list in a shopping cart summary |
| `.strip()` | `" user123 ".strip()` | `'user123'` | Cleaning form inputs before storing in a database |
| `.replace()` | `"pass123".replace("pass", "***")` | `'***123'` | Masking sensitive data (like passwords or IDs) in logs |
| `.upper()` | `"lorenzo".upper()` | `'LORENZO'` | Standardizing usernames or country codes before saving |
| `.lower()` | `"`[`USER@EMAIL.COM`](mailto:USER@EMAIL.COM)`".lower()` | `'`[`user@email.com`](mailto:user@email.com)`'` | Normalizing emails for case-insensitive login validation |
| `.capitalize()` | `"python is great".capitalize()` | `'Python is great'` | Formatting short descriptions in blog previews |
| `.title()` | `"the great gatsby".title()` | `'The Great Gatsby'` | Displaying book or article titles in a reading app |
| `.startswith()` | `"`[`https://example.com".startswith("https://`](https://example.com%22.startswith\(%22https://)`")` | `True` | Verifying URL security before redirecting or scraping |
| `.endswith()` | `"resume.pdf".endswith(".pdf")` | `True` | Validating uploaded documents to allow only PDFs |
| `.find()` | `"`[`support@email.com`](mailto:support@email.com)`".find("@")` | `7` | Validating email syntax by checking position of "@" |
| `.count()` | `"banana".count("a")` | `3` | Counting keyword frequency in reviews for sentiment scoring |
| `.isdigit()` | `"12345".isdigit()` | `True` | Verifying that age or phone number fields contain only digits |
| `.isalpha()` | `"Lorenzo".isalpha()` | `True` | Validating names to ensure no numbers or special characters |

---

njk

### 9️⃣ User Input in Python

The `input()` function allows you to take text input from the user during a program’s execution.

When this runs, Python:

* Shows the message (prompt)
    
* Waits for the user to type something
    
* Stores the input as a **string**, even if it looks like a number.
    

```python
age = input("How old are you? ")
print("You are", age, "years old.")
```

**User Input:** `23`

**Example Output:**

```python
How old are you? 23
You are 23 years old.
```

---

### 🔄 Converting Input to Numbers

When you use `input()`, the result is always a **string** — even if the user enters a number. To use the input as a number, convert it:

| **Conversion** | **Example** | **Resulting Type** |
| --- | --- | --- |
| `int()` | `int("25")` → `25` | Integer |
| `float()` | `float("3.14")` → `3.14` | Float |
| `str()` | `str(42)` → `"42"` | String |

```python
birth_year = input("Enter your birth year: ")
age = 2025 - int(birth_year)
print("You are", age, "years old.")
```

**User Input:** `1987`

**Output:**

```python
Enter your birth year: 1987
You are 38 years old.
```

---

### ✨ Cleaning and Formatting Input

Use `.strip()` and `.capitalize()` to clean and format raw user input:

```python
raw_name = input("Enter your first name: ")

# Clean and format the input
cleaned_name = raw_name.strip().capitalize()

print("Hello,", cleaned_name)
```

**User Input:** `lorenzo nicholas`

**Output:**

```python
Enter your first name: lorenzo nicholas
Hello, Lorenzo nicholas
```

---

### ✅ Example 1: Validating Age Input (Check if Input Is a Number)

```python
age_input = input("Enter your age: ")

if age_input.isdigit():
    age = int(age_input)
    print("You will be", age + 1, "next year.")
else:
    print("❌ Invalid input. Please enter a number.")
```

**User Input:** `dg`

**Output:**

```python
Enter your age: dg
❌ Invalid input. Please enter a number.
```

---

### ✅ Example 2: Validating a Name Field (Only Letters Allowed)

```python
name = input("Enter your first name: ")

if name.isalpha():
    print("Hello,", name.capitalize())
else:
    print("❌ Names should only contain letters. Try again.")
```

**User Input:** `xdgx`

**Output:**

```python
Enter your first name: xdgx
Hello, Xdgx
```

---

### ✅ Real-World Example: Taking Subject Marks in One Line

```python
marks_input = input("Enter your marks for Math, Science, and English (separated by spaces): ")

# Split the input into separate values
marks = marks_input.split()

# Convert strings to integers
math, science, english = int(marks[0]), int(marks[1]), int(marks[2])

# Calculate average
average = (math + science + english) / 3

print("Average mark:", round(average, 2))
```

**User Input:** `34 56 89`

**Output:**

```python
Enter your marks for Math, Science, and English (separated by spaces): 34 56 89
Average mark: 59.67
```

### 🔟 Escape Characters in Strings

Escape characters start with a backslash `\` and tell Python to treat the next character in a special way.

| Escape | Meaning | Example Code | Output |
| --- | --- | --- | --- |
| `\n` | New line | `print("Hello\nWorld")` | HelloWorld |
| `\t` | Horizontal tab (indent) | `print("Name:\tLorenzo")` | Name: Lorenzo |
| `\\` | Backslash character (`\`) | `print("Path: C:\\User\\Files")` | Path: C:\\User\\Files |
| `\'` | Single quote | `print('It\'s Python')` | It's Python |
| `\"` | Double quote | `print("She said: \"Hello\"")` | She said: "Hello" |

### 🔹 `\n` – New Line

```python
print("Hello\nWorld")
```

**Output:**

```python
Hello
World
```

### 🔹 `\t` – Horizontal Tab

```python
print("Name:\tLorenzo")
```

**Output:**

```python
Name:	Lorenzo
```

### 🔹 `\\` – Backslash Character

```python
print("Path: C:\\User\\Files")
```

**Output:**

```python
Path: C:\User\Files
```

### 🔹 `\'` – Single Quote Inside Single-Quoted String

```python
print('It\'s Python')
```

**Output:**

```python
It's Python
```

### 🔹 `\"` – Double Quote Inside Double-Quoted String

```python
print("She said: \"Hello\"")
```

**Output:**

```python
She said: "Hello"
```

---

### 1️⃣1️⃣ Multi-line Strings in Python (`"""..."""`)

Multi-line strings allow you to store or display text that spans multiple lines without needing `\n` manually.

You can define them using:

```python
"""Triple double quotes"""
'''Triple single quotes'''
```

✅ Line breaks are preserved as you write them.

### Example:

```python
message = """Dear Lorenzo,

Thank you for registering.
We hope you enjoy the course.

Regards,
Team Python
"""

print(message)
```

**Output:**

```python
Dear Lorenzo,

Thank you for registering.
We hope you enjoy the course.

Regards,
Team Python
```
