Docsity

Regular Expressions in Python: String Manipulation and Pattern Matching, Summaries of Machine Learning

Partial preview of the text

Download Regular Expressions in Python: String Manipulation and Pattern Matching and more Summaries Machine Learning in PDF only on Docsity!

Introduction to

string manipulation

R E G U L A R E X P R E S S I O N S I N P Y T H O N

Maria Eugenia Inzaugarat

Data Scientist

You will learn

String manipulation e.g. replace and nd specic substrings

String formatting e.g. interpolating a string in a template

Basic and advanced regular expressions e.g. nding complex patterns in a string

Strings

Sequence of characters

Quotes

my_string = "This is a string" my_string2 = 'This is also a string'

my_string = 'And this? It's the wrong string'

my_string = "And this? It's the correct string"

More strings

Length

my_string = "Awesome day" len(my_string)

Convert to string

str(123)

Indexing

Bracket notation (^) my_string = "Awesome day"

print(my_string[3])

s

print(my_string[-1])

y

Slicing

Bracket notation (^) my_string = "Awesome day" print(my_string[0:3])

Awe

print(my_string[:5]) print(my_string[5:])

Aweso me day

Let's practice!

String operations

R E G U L A R E X P R E S S I O N S I N P Y T H O N

Maria Eugenia Inzaugarat

Data Scientist

my_string = "tHis Is a niCe StriNg"

Capitalizing the rst character

print(my_string.capitalize())

This is a nice string

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']

Breaking at line boundaries

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

my_string.splitlines()

['This string will be split', 'in two']

Joining

Concatenate strings from list or another iterable

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

this would be a string

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'

Let's practice!