7. Chaînes et bytes

str, méthodes, f-strings, formatage, bytes, bytearray, encodage Unicode.


7.1 Chaînes (str)

Immuables, séquences de caractères Unicode.

s = "Hello"
s = 'Hello'          # simple ou double quote
s = """Multi
lignes"""            # triple quotes

Échappement

"ligne1\nligne2"      # \n nouvelle ligne
"tab\tici"            # \t tabulation
"c:\\chemin"           # \\ backslash
r"c:\chemin"          # raw string (pas d'échappement)

Méthodes principales

s.upper() / s.lower() / s.title()
s.strip() / s.lstrip() / s.rstrip()
s.startswith("He") / s.endswith("lo")
s.find("el")          # index ou -1
s.index("el")         # index ou ValueError
s.replace("l", "L")   # "HeLLo"
s.split(",")          # ["part1", "part2"]
", ".join(["a", "b"])  # "a, b"
s.count("l")          # 2
"123".isdigit()       # True
"abc".isalpha()       # True
len(s)

7.2 F-strings (PEP 498)

nom = "Alice"
âge = 30
print(f"{nom} a {âge} ans")        # "Alice a 30 ans"
print(f"{nom:>10}")                # "     Alice" (aligné à droite)
print(f"{âge:03d}")                # "030"
print(f"{3.14159:.2f}")            # "3.14"
print(f"{1000:,}")                 # "1,000"
print(f"{0.5:.0%}")                # "50%"

Expressions :

print(f"{2 ** 10}")                # 1024
print(f"{nom.upper()}")            # ALICE

7.3 .format()

"{}, {} !".format("Bonjour", "monde")
"{1}, {0}".format("monde", "Bonjour")
"{nom} a {âge} ans".format(nom="Alice", âge=30)

7.4 Slicing de chaînes

Comme les listes :

s = "Bonjour"
s[0]      # "B"
s[-1]     # "r"
s[2:5]    # "njo"
s[::-1]   # "ruojnoB"

7.5 Unicode

Python 3 : str = Unicode. Encodage/décodage avec bytes :

s = "éèçàñ"
b = s.encode("utf-8")    # bytes (b'\xc3\xa9...')
s2 = b.decode("utf-8")   # str

7.6 bytes et bytearray

bytes : immuable, séquence d’octets (0-255).

b = b"hello"              # bytes littéral
b = bytes([104, 101, 108, 108, 111])
b[0]                      # 104

bytearray : muable.

ba = bytearray(b"hello")
ba[0] = 72                # 72 = 'H'

7.7 ord() et chr()

ord("A")    # 65 (code Unicode)
chr(65)     # "A"
ord("é")    # 233

7.8 Test de membership

"ab" in "abcde"   # True
"z" not in "abc"  # True

🔗 ← Retour au cours · ← précédent · Suivant →