Os métodos de string Python estão entre as ferramentas usadas com mais frequência no kit de ferramentas de qualquer desenvolvedor Python. Em 2026, dominar a manipulação de strings é essencial para web scraping, limpeza de dados, trabalho de API e processamento de texto. Este guia completo cobre todos os métodos importantes de strings com exemplos práticos.
📋 Table of Contents
Métodos essenciais de string
# String creation and basic info
text = " Hello, Python World! "
print(len(text)) # 24 (including spaces)
print(type(text)) # <class 'str'>
# Case transformation
print(text.upper()) # " HELLO, PYTHON WORLD! "
print(text.lower()) # " hello, python world! "
print(text.title()) # " Hello, Python World! "
print(text.capitalize()) # " hello, python world! " (only first char)
print(text.swapcase()) # " hELLO, pYTHON wORLD! "
# Whitespace removal
print(text.strip()) # "Hello, Python World!" (both sides)
print(text.lstrip()) # "Hello, Python World! " (left only)
print(text.rstrip()) # " Hello, Python World!" (right only)
print(text.strip("!. ")) # removes those chars from both ends
Métodos de pesquisa e teste
s = "Hello, Python World!"
# Finding substrings
print(s.find("Python")) # 7 (returns -1 if not found)
print(s.index("Python")) # 7 (raises ValueError if not found)
print(s.rfind("l")) # 14 (search from right)
print(s.count("l")) # 3
# Boolean checks
print(s.startswith("Hello")) # True
print(s.endswith("!")) # True
print(s.startswith(("Hi", "Hello"))) # True (tuple of prefixes)
# Content checks
print("abc123".isalnum()) # True (only alphanumeric)
print("Hello".isalpha()) # True (only letters)
print("12345".isdigit()) # True (only digits)
print(" ".isspace()) # True (only whitespace)
print("HELLO".isupper()) # True
print("hello".islower()) # True
print("Python 3.12".isprintable()) # True
Métodos de modificação
# Replace
s = "Hello World Hello"
print(s.replace("Hello", "Hi")) # "Hi World Hi"
print(s.replace("Hello", "Hi", 1)) # "Hi World Hello" (max 1 replacement)
# Split and join
csv = "Alice,Bob,Carol,Dave"
print(csv.split(",")) # ["Alice", "Bob", "Carol", "Dave"]
print(csv.split(",", 2)) # ["Alice", "Bob", "Carol,Dave"] (max 2 splits)
lines = "line1
line2
line3"
print(lines.splitlines()) # ["line1", "line2", "line3"]
# Join — build string from list
words = ["Python", "is", "awesome"]
print(" ".join(words)) # "Python is awesome"
print("-".join(words)) # "Python-is-awesome"
print("".join(["a","b","c"])) # "abc"
# Padding and alignment
print("hello".center(11, "*")) # "***hello***"
print("hi".ljust(10, ".")) # "hi........"
print("hi".rjust(10, ".")) # "........hi"
print("42".zfill(5)) # "00042" (zero-fill for numbers)
Métodos de formato e modelo
# f-strings (best, Python 3.6+)
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
print(f"Pi: {3.14159:.2f}") # Pi: 3.14
print(f"Hex: {255:#010x}") # Hex: 0x000000ff
print(f"1000000: {1_000_000:,}") # 1000000: 1,000,000
# format() method
print("Hello, {}!".format(name))
print("{0} + {1} = {2}".format(2, 3, 2+3))
print("{name} is {age}".format(name="Bob", age=25))
# Template strings (safe for user input)
from string import Template
t = Template("Hello, $name!")
print(t.substitute(name="Alice")) # "Hello, Alice!"
print(t.safe_substitute()) # "Hello, $name!" (no KeyError)
# encode/decode
s = "Hello, 世界"
encoded = s.encode("utf-8") # bytes
decoded = encoded.decode("utf-8") # string back
Processamento de strings no mundo real
# Clean user input
def clean_username(raw: str) -> str:
return raw.strip().lower().replace(" ", "_")[:30]
# Parse CSV line
def parse_csv_line(line: str) -> list[str]:
return [field.strip().strip('"') for field in line.split(",")]
# Validate email (simple)
def is_valid_email(email: str) -> bool:
email = email.strip().lower()
return "@" in email and "." in email.split("@")[1]
# Extract numbers from string
import re
text = "I have 3 cats and 12 dogs"
numbers = [int(n) for n in re.findall(r'\d+', text)] # [3, 12]
# Camel to snake case
def camel_to_snake(name: str) -> str:
s = re.sub(r'([A-Z]+)([A-Z][a-z])', r'_', name)
return re.sub(r'([a-z\d])([A-Z])', r'_', s).lower()
# Truncate with ellipsis
def truncate(text: str, max_len: int = 100) -> str:
return text[:max_len-3] + "..." if len(text) > max_len else text
Os métodos de string Python são a base do processamento de texto. Master strip/split/join para limpeza de dados, localizar/substituir para transformação de texto e formatar strings para saída. A combinação de cordas F (modernas) e split/join cobre 90% do trabalho diário com cordas.
🔗 Share this article
✍️ Leave a Comment