# 5. Manipulacao de Strings e F Strings

## Introdução

Como Python é frequentemente utilizado para processar logs, gerar payloads e criar relatórios, o domínio da manipulação de strings é essencial para qualquer pentester.

## Formatação de Strings (A Evolução)

{% stepper %}
{% step %}

### Old Style (% operador) - Legado

```python
nome = "admin"
print("Olá, %s" % nome)
```

{% endstep %}

{% step %}

### `.format()` - Mais flexível

```python
print("Alvo: {} Porta: {}".format("10.0.0.1", 80))
```

{% endstep %}

{% step %}

### F-Strings (Python 3.6+) - **Recomendado**

As f-strings são rápidas e permitem embutir expressões diretamente.

```python
ip = "192.168.1.1"
porta = 443
print(f"Tentando conexão em {ip}:{porta}")
```

{% endstep %}
{% endstepper %}

## Métodos de String Essenciais

| Método                              | Descrição                                   | Exemplo                        |
| ----------------------------------- | ------------------------------------------- | ------------------------------ |
| **`.lower()` / `.upper()`**         | Converte para minúsculo/maiúsculo.          | `"ADMIN".lower()`              |
| **`.strip()`**                      | Remove espaços (ou chars) nas extremidades. | `" log ".strip()`              |
| **`.split()`**                      | Divide a string em uma lista.               | `"1,2,3".split(",")`           |
| **`.join()`**                       | Junta uma lista em uma string.              | `",".join(["A", "B"])`         |
| **`.replace()`**                    | Substitui trechos da string.                | `"alvo".replace("o", "a")`     |
| **`.startswith()` / `.endswith()`** | Verifica início ou fim.                     | `"http://".startswith("http")` |

## Fatiamento (Slicing)

Extremamente útil para extrair sub-strings sem usar regex complexo.\
Sintaxe: `string[inicio:fim:passo]`

```python
hash_md5 = "e10adc3949ba59abbe56e057f20f883e"
primeiros_8 = hash_md5[:8]  # e10adc39
ultimos_4 = hash_md5[-4:]   # 883e
invertida = hash_md5[::-1]  # Inverte a string
```

## Escaping e Raw Strings

Para lidar com caminhos do Windows ou expressões regulares sem sofrer com o caractere de escape `\`.

```python
# String Normal (necessita escape)
caminho = "C:\\Windows\\System32"

# Raw String (prefixo 'r')
caminho_raw = r"C:\Windows\System32"
```

## Cores no Terminal

Diferente do Bash que usa códigos ANSI diretamente (`\e[31m`), no Python você pode usar f-strings com códigos ANSI ou bibliotecas como `colorama`.

```python
# Usando códigos ANSI manuais
VERMELHO = "\033[31m"
RESET = "\033[0m"

print(f"{VERMELHO}[!] Alerta de Segurança{RESET}")
```

## Boas Práticas

1. **Use F-Strings:** São as mais legíveis e performáticas.
2. **Strings imutáveis:** Lembre-se que métodos de string retornam uma **nova** string, eles não alteram a original.
3. **Encoding:** Ao lidar com pacotes de rede ou arquivos, você precisará converter de `str` para `bytes` e vice-versa:

   ```python
   payload = "A" * 100
   socket.send(payload.encode("utf-8"))

   data = socket.recv(1024).decode("utf-8")
   ```

{% hint style="info" %}
Use `.strip().split()` em sequência para limpar e processar linhas de um arquivo de configuração ou uma wordlist de forma rápida.
{% endhint %}


---

# 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://0xmorte.gitbook.io/bibliadopentestbr/conceitos/programacao-e-linguagens/python/5.-manipulacao-de-strings-e-f-strings.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.
