Operații cu șiruri de caractere

Expresii regulate în Python

Maria Eugenia Inzaugarat

Data Scientist

Modificarea majusculelor

my_string = "tHis Is a niCe StriNg"
  • Conversie la litere mici
print(my_string.lower())
this is a nice string
  • Conversie la litere mari
print(my_string.upper())
THIS IS A NICE STRING
Expresii regulate în Python

 

my_string = "tHis Is a niCe StriNg"

 

  • Punerea cu majusculă a primului caracter
print(my_string.capitalize())
This is a nice string
Expresii regulate în Python

Împărțirea șirurilor

my_string = "This string will be split"
  • Împarte un șir într-o listă de subșiruri
my_string.split(sep=" ", maxsplit=2)
['This', 'string', 'will be split']
my_string.rsplit(sep=" ", maxsplit=2)
['This string will', 'be', 'split']
Expresii regulate în Python

 

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

print(my_string)
This string will be split
in two

Expresii regulate în Python
  • Împărțire la limitele de linie
my_string = "This string will be split\nin two"

 

my_string.splitlines()
['This string will be split', 'in two']
Expresii regulate în Python

Îmbinarea șirurilor

  • Concatenează șiruri dintr-o listă sau alt iterabil

 

my_list = ["this", "would", "be", "a", "string"]
print(" ".join(my_list))
this would be a string
Expresii regulate în Python

Eliminarea caracterelor

  • Elimină caractere de la stânga și dreapta: .strip()

 

my_string = " This string will be stripped\n"
my_string.strip()
'This string will be stripped'
Expresii regulate în Python

 

my_string = " This string will be stripped\n"
  • Elimină caractere de la capătul din dreapta
my_string.rstrip()
' This string will be stripped'
  • Elimină caractere de la capătul din stânga
my_string.lstrip()
'This string will be stripped\n'
Expresii regulate în Python

Să exersăm!

Expresii regulate în Python

Preparing Video For Download...