> ## Documentation Index
> Fetch the complete documentation index at: https://rajanand.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Strings

## 1. **What is a String?**

* A **string** is a sequence of characters enclosed in quotes.
* Strings are immutable, meaning their contents cannot be changed after creation.
* Python supports single quotes (`'`), double quotes (`"`), and triple quotes (`'''` or `"""`) for defining strings.

**Examples**:

```python theme={"system"}
name = "Raj"
message = 'Hello, World!'
paragraph = """This is a multi-line
string in Python."""
```

## 2. **String Operations**

### **1. Concatenation**

* Combining two or more strings using the `+` operator.

**Example**:

```python theme={"system"}
first_name = "Ram"
last_name = "Kumar"
full_name = first_name + " " + last_name
print(full_name)  # Output: Ram Kumar
```

### **2. Repetition**

* Repeating a string using the `*` operator.

**Example**:

```python theme={"system"}
greeting = "Hello! "
print(greeting * 3)  # Output: Hello! Hello! Hello!
```

### **3. Indexing**

* Accessing individual characters in a string using their index.
* Python uses zero-based indexing (the first character has index `0`).

**Example**:

```python theme={"system"}
name = "Anand"
print(name[0])  # Output: A
print(name[-1])  # Output: d (negative indexing starts from the end)
```

### **4. Slicing**

* Extracting a substring using a range of indices.
* Syntax: `string[start:stop:step]`

**Examples**:

```python theme={"system"}
text = "Python Programming"
print(text[0:6])  # Output: Python (from index 0 to 5)
print(text[7:])   # Output: Programming (from index 7 to the end)
print(text[:6])   # Output: Python (from the start to index 5)
print(text[::2])  # Output: Pto rgamn (every second character)
```

### **5. Length**

* Finding the length of a string using the `len()` function.

**Example**:

```python theme={"system"}
name = "Bala"
print(len(name))  # Output: 4
```

## 3. **String Methods**

### **1. `upper()` and `lower()`**

* Convert a string to uppercase or lowercase.

**Example**:

```python theme={"system"}
text = "Hello, World!"
print(text.upper())  # Output: HELLO, WORLD!
print(text.lower())  # Output: hello, world!
```

### **2. `strip()`, `lstrip()`, and `rstrip()`**

* Remove leading and trailing whitespace (or specified characters).

**Example**:

```python theme={"system"}
text = "   Python   "
print(text.strip())  # Output: Python
```

### **3. `replace()`**

* Replace a substring with another substring.

**Example**:

```python theme={"system"}
text = "Hello, World!"
new_text = text.replace("World", "Karthik")
print(new_text)  # Output: Hello, Karthik!
```

### **4. `split()`**

* Split a string into a list of substrings based on a delimiter.

**Example**:

```python theme={"system"}
text = "Python,Java,C++"
languages = text.split(",")
print(languages)  # Output: ['Python', 'Java', 'C++']
```

### **5. `join()`**

* Join a list of strings into a single string using a delimiter.

**Example**:

```python theme={"system"}
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)  # Output: Python is fun
```

### **6. `find()` and `index()`**

* Find the index of a substring in a string.
* `find()` returns `-1` if the substring is not found, while `index()` raises an error.

**Example**:

```python theme={"system"}
text = "Hello, World!"
print(text.find("World"))  # Output: 7
print(text.index("World"))  # Output: 7
```

### **7. `startswith()` and `endswith()`**

* Check if a string starts or ends with a specific substring.

**Example**:

```python theme={"system"}
text = "Hello, World!"
print(text.startswith("Hello"))  # Output: True
print(text.endswith("!"))        # Output: True
```

### **8. `isalpha()`, `isdigit()`, `isalnum()`**

* Check if all characters in a string are alphabetic, numeric, or alphanumeric.

**Example**:

```python theme={"system"}
print("Python".isalpha())  # Output: True
print("123".isdigit())     # Output: True
print("Python3".isalnum()) # Output: True
```

## 4. **String Formatting**

### **1. `f-strings` (Python 3.6+)**

* Embed expressions inside string literals using `{}`.

**Example**:

```python theme={"system"}
name = "David"
age = 30
print(f"{name} is {age} years old.")  # Output: David is 30 years old.
```

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

* Insert values into a string using placeholders `{}`.

**Example**:

```python theme={"system"}
name = "Kannan"
age = 25
print("{0} is {1} years old.".format(name, age))  # Output: Kannan is 25 years old.
```

### **3. `%` Formatting (Older Style)**

* Use `%` as a placeholder for values.

**Example**:

```python theme={"system"}
name = "Siva"
age = 28
print("%s is %d years old." % (name, age))  # Output: Siva is 28 years old.
```

## 5. **Escape Sequences**

* Special characters used to represent non-printable or special characters in strings.
* Common escape sequences:
  * `\n`: Newline
  * `\t`: Tab
  * `\\`: Backslash
  * `\"`: Double quote
  * `\'`: Single quote

**Example**:

```python theme={"system"}
print("Hello\nWorld!")  # Output: Hello
                        #         World!
```

## 6. **Additional Examples**

* **Concatenation**:
  ```python theme={"system"}
  first_name = "Suresh"
  last_name = "Kumar"
  full_name = first_name + " " + last_name
  print(full_name)  # Output: Suresh Kumar
  ```

* **Slicing**:
  ```python theme={"system"}
  name = "Sathish"
  print(name[0:4])  # Output: Sath
  ```

* **String Methods**:
  ```python theme={"system"}
  text = "   Sujatha   "
  print(text.strip())  # Output: Sujatha
  ```

* **String Formatting**:
  ```python theme={"system"}
  name = "Kavitha"
  age = 22
  print(f"{name} is {age} years old.")  # Output: Kavitha is 22 years old.
  ```

## 7. **Best Practices**

* Use `f-strings` for string formatting (Python 3.6+).
* Use triple quotes for multi-line strings.
* Avoid using `+` for concatenating many strings (use `join()` instead for efficiency).
