Opérations sur les chaînes

Expressions rationnelles en Python

Maria Eugenia Inzaugarat

Data Scientist

Ajuster la casse

my_string = "tHis Is a niCe StriNg"
  • Conversion en minuscules
print(my_string.lower())
this is a nice string
  • Conversion en majuscules
print(my_string.upper())
THIS IS A NICE STRING
Expressions rationnelles en Python

 

my_string = "tHis Is a niCe StriNg"

 

  • Mettre la première lettre en majuscule
print(my_string.capitalize())
This is a nice string
Expressions rationnelles en Python

Découpage

my_string = "This string will be split"
  • Découper une chaîne en sous-chaînes
my_string.split(sep=" ", maxsplit=2)
['This', 'string', 'will be split']
my_string.rsplit(sep=" ", maxsplit=2)
['This string will', 'be', 'split']
Expressions rationnelles en Python

 

my_string = "This string will be split\nin two"

print(my_string)
This string will be split
in two

Expressions rationnelles en Python
  • Séparer aux limites de ligne
my_string = "This string will be split\nin two"

 

my_string.splitlines()
['This string will be split', 'in two']
Expressions rationnelles en Python

Jointure

  • Concaténer des chaînes depuis une liste ou un autre itérable

 

my_list = ["this", "would", "be", "a", "string"]
print(" ".join(my_list))
this would be a string
Expressions rationnelles en Python

Suppression de caractères

  • Supprimer des caractères des deux côtés : .strip()

 

my_string = " This string will be stripped\n"
my_string.strip()
'This string will be stripped'
Expressions rationnelles en Python

 

my_string = " This string will be stripped\n"
  • Supprimer à droite
my_string.rstrip()
' This string will be stripped'
  • Supprimer à gauche
my_string.lstrip()
'This string will be stripped\n'
Expressions rationnelles en Python

Passons à la pratique !

Expressions rationnelles en Python

Preparing Video For Download...