pvdocs /Python/Manipulação de Strings

Manipulação de Strings

Strings in Python are immutable sequences of Unicode characters.

Common Methods

s = "  Hello, World!  "

s.strip()                      # "Hello, World!"
s.lower() / s.upper()          # case conversion
s.replace("World", "Python")   # "  Hello, Python!  "
s.startswith("  H")            # True
s.endswith("!  ")              # True
s.count("l")                   # 3
s.find("World")                # 9  (-1 if not found)
s.index("World")               # 9  (ValueError if not found)
"  hi  ".lstrip() / .rstrip()  # strip only left or right

Split and Join

csv   = "a,b,c,d"
parts = csv.split(",")      # ['a', 'b', 'c', 'd']
back  = ",".join(parts)     # 'a,b,c,d'

# split without arg splits on any whitespace
"foo   bar\tbaz".split()    # ['foo', 'bar', 'baz']

lines = "a\nb\nc".splitlines()  # ['a', 'b', 'c']

Slicing

s = "Python"
s[0]    # 'P'
s[-1]   # 'n'
s[1:4]  # 'yth'
s[::-1] # 'nohtyP'  — reversed
s[::2]  # 'Pto'    — every other character

Formatting

name, score = "Alice", 98.5

# f-string — preferred (Python 3.6+)
f"Hello, {name}! Score: {score:.1f}"

# str.format()
"Hello, {}! Score: {:.1f}".format(name, score)

f-string Format Specs

f"{1234567:,}"       # '1,234,567'    — thousand separator
f"{3.14159:.2f}"     # '3.14'         — 2 decimal places
f"{42:05d}"          # '00042'        — zero-padded
f"{'hi':<10}"        # 'hi        '   — left-align
f"{'hi':>10}"        # '        hi'   — right-align
f"{'hi':^10}"        # '    hi    '   — center
f"{255:#x}"          # '0xff'         — hex with prefix

Checking Content

"hello".isalpha()    # True — all letters
"123".isdigit()      # True — all digits
"abc123".isalnum()   # True
"   ".isspace()      # True
"Hello World".istitle()  # True

String ↔ Bytes

b = "café".encode("utf-8")   # b'caf\xc3\xa9'
s = b.decode("utf-8")        # 'café'

Key Interview Points