Python Zero to Heros

Online Absolute Beginner Python Tutorials 

Every Sunday 2pm (UK time/ BST)

Get this slide deck: https://slides.com/cheukting_ho/python-strings-regex

Recap

Python objects - int, float, str, list, dict, bool

Control flows - if-else, for loop, while loop

Functions, modeuls, classes and decorators

pytest

 

Any Questions?

String Operations

Rrcap: "adding" two strings "+", f-strings

greeting = "Hello" + " " + "World"
more_greeting = f"Hey {greeting}! Do you want some tractor jokes?"

You can also use "join"

hello_list = ["Hello", "World"]
" ".join(hello_list)

How about breaking them?

String Operations

greeting.split()
"what is www mean?".split('w')
"Happy!!!Sunday!".split("!!!")
"There_are/lots#of_special/characters".split("_/#")

Can I spint with multiple option? (Spoilor: Regex)

Other manipulations

"Hello World".lower()
"Hello World".upper()
"hello world".capitalize()
"!!!!!Yay it's Sunday!!".replace('!',' ')
"    Hello     ".strip()
"!!!!!Yay it's Sunday!!".strip('!')
"    Yay it's Sunday !!!  ".strip(" !")

Regex

What is Regex?

A regular expression (shortened as regex or regexp; also referred to as rational expression) is a sequence of characters that define a search pattern. - wikipedia

 

Example

Whole Numbers – /^\d+$/

Common email Ids – /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$/

Time Format HH:MM:SS 24-hour
/(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/

 

https://regex101.com/

import re

that_sentance = "There_are/lots#of_special/characters"
re.split("[_/#]",that_sentance)

Regex

Replace a pattern

import re

that_sentance = "There_are/lots#of_special/characters"
re.sub("[_/#]"," ",that_sentance)

Regex

Searching for a pattern

import re

that_sentance = "There_are/lots#of_special/characters"
re.search("[_/#]",that_sentance)
re.search("re",that_sentance)
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'
>>> m.group(2)       # The second parenthesized subgroup.
'Newton'

You can also check the "span()"

Let's try writing some properties

 

Simple E-comerce similator ( e-shop.py)

Can you validate the user's email address?

 

https://github.com/Cheukting/python02hero/tree/master/2020-05-31-python-strings-regex

Homework 📝

 

There is no homework :-)

Next week:
Mocking/ patching in Pytest

Sunday 2pm (UK time/ BST)

There are also Mid Meet Py every Wednesday 1pm

Testing month in June

Python Strings and Regex

By Cheuk Ting Ho

Python Strings and Regex

  • 970