# Строки и их методы

### **1. Что такое строка**

* Строка (`str`) — это **неизменяемая последовательность символов**.
* Можно создавать с помощью **одинарных `'...'`**, **двойных `"..."`**, либо **тройных кавычек `'''...'''` / `"""..."""`** для многострочного текста.

```python
s1 = "Hello"
s2 = 'World'
s3 = """Многострочный
текст"""
```

***

### **2. Основные методы строк**

| Метод                           | Описание                                     | Пример                                         |
| ------------------------------- | -------------------------------------------- | ---------------------------------------------- |
| `str.upper()`                   | Преобразует в верхний регистр                | `"hello".upper()` → `"HELLO"`                  |
| `str.lower()`                   | Преобразует в нижний регистр                 | `"HELLO".lower()` → `"hello"`                  |
| `str.title()`                   | Заглавная буква у каждого слова              | `"hello world".title()` → `"Hello World"`      |
| `str.capitalize()`              | Заглавная буква у первого слова              | `"hello world".capitalize()` → `"Hello world"` |
| `str.strip()`                   | Убирает пробелы или символы с начала и конца | `" text ".strip()` → `"text"`                  |
| `str.lstrip()` / `str.rstrip()` | Убирает пробелы слева/справа                 | `" text".lstrip()` → `"text"`                  |
| `str.replace(old, new)`         | Замена подстроки                             | `"foo".replace("f","b")` → `"boo"`             |
| `str.split(sep=None)`           | Разделяет строку на список                   | `"a,b,c".split(",")` → `['a','b','c']`         |
| `str.join(iterable)`            | Объединяет элементы списка                   | `",".join(['a','b','c'])` → `"a,b,c"`          |
| `str.startswith(prefix)`        | Проверка начала строки                       | `"hello".startswith("he")` → `True`            |
| `str.endswith(suffix)`          | Проверка окончания строки                    | `"hello".endswith("lo")` → `True`              |
| `str.find(sub)`                 | Индекс подстроки или -1                      | `"hello".find("l")` → `2`                      |
| `str.count(sub)`                | Количество вхождений                         | `"hello".count("l")` → `2`                     |
| `str.isdigit()`                 | Все символы цифры                            | `"123".isdigit()` → `True`                     |
| `str.isalpha()`                 | Все символы буквы                            | `"abc".isalpha()` → `True`                     |
| `str.isalnum()`                 | Все символы буквы или цифры                  | `"abc123".isalnum()` → `True`                  |

***

### **3. Особенности строк**

1. **Неизменяемость**
   * Любая операция возвращает **новый объект**, оригинал не меняется.

```python
s = "hello"
s.upper()  # "HELLO", но s всё ещё "hello"
```

2. **Индексация и срезы**

```python
s = "hello"
print(s[0])   # 'h'
print(s[-1])  # 'o'
print(s[1:4]) # 'ell'
```

3. **Поддержка логических операций**

* `in` / `not in`:

```python
"he" in "hello"  # True
```

***

### **4. Применение в автотестах**

* **Проверка текста в API или UI**

```python
response = "Success: user created"
assert "Success" in response
```

* **Обработка данных и логов**

```python
line = "  ERROR: Invalid input  "
assert line.strip().startswith("ERROR")
```

* **Разделение и объединение данных**

```python
csv = "a,b,c"
fields = csv.split(",")
assert ",".join(fields) == csv
```

* **Валидация формата**

```python
username = "Alice123"
assert username.isalnum()  # только буквы и цифры
```

***

💡 **Вывод:**

* Строки — **неизменяемые последовательности символов**, поддерживают методы для **изменения регистра, поиска, замены, разбиения и объединения**.
* Очень полезны для **обработки текста, логов, данных API и проверок UI** в автотестах.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kaze.gitbook.io/qa-theory/osnovy-programmirovaniya-na-python/stroki-i-ikh-metody.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
