String operations

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Adjusting cases

my_string = "tHis Is a niCe StriNg"
  • Converting to lowercase
print(my_string.lower())
this is a nice string
  • Converting to uppercase
print(my_string.upper())
THIS IS A NICE STRING
Regular Expressions in Python

 

my_string = "tHis Is a niCe StriNg"

 

  • Capitalizing the first character
print(my_string.capitalize())
This is a nice string
Regular Expressions in Python

Splitting

my_string = "This string will be split"
  • Splitting a string into a list of substrings
my_string.split(sep=" ", maxsplit=2)
['This', 'string', 'will be split']
my_string.rsplit(sep=" ", maxsplit=2)
['This string will', 'be', 'split']
Regular Expressions in Python

 

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

print(my_string)
This string will be split
in two

Regular Expressions in Python
  • Breaking at line boundaries
my_string = "This string will be split\nin two"

 

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

Joining

  • Concatenate strings from list or another iterable

 

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

Stripping characters

  • Strips characters from left to right: .strip()

 

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

 

my_string = " This string will be stripped\n"
  • Remove characters from the right end
my_string.rstrip()
' This string will be stripped'
  • Remove characters from the left end
my_string.lstrip()
'This string will be stripped\n'
Regular Expressions in Python

Let's practice!

Regular Expressions in Python

Preparing Video For Download...