8_String and Regular Expression
8_String and Regular Expression
Unchangeable
Working with Strings
Length
Practice
1. Counting the number of characters in a string.
Sample String : google.com'
Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1,
'm': 1}
String Methods
.title( ),
.upper(),
.lower(),
.rstrip(),
.lstrip(),
.strip()
String Methods
.replace():
The replace method works like a find and replace tool. It takes in
two values within its parenthesis, one that it searches for and the
other that it replaces the searched value.
Syntax
string.replace(oldvalue, newvalue, count)
String Methods
Parameter Values
Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value
you want to replace. Default is all occurrences
String Methods
.find( ):
The find method will search for any string we ask it to. It
finds the starting index of our searched term.
Syntax
string.find(value, start, end)
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to
the end of the string
\d Returns a match where the string contains digits (numbers from 0-9)
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string
Practice
Get full names, emails, and phone numbers in the file Example_Regex.txt
• Emails: [a-z]+@[a-z.]+
• Name: (?:[A-ZĐ]\w+\s){3,4} or
Try it yourself
• (?:[A-ZĐ][a-záàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợíìỉĩịúùủũụưứừửữựýỳỷỹỵđ,]+\s){3,4}
• (?:[A-ZĐ][a-záàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợíìỉĩịúùủũụưứừửữựýỳỷỹỵ]+\s){2,3}[A-ZĐ][a-
záàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợíìỉĩịúùủũụưứừửữựýỳỷỹỵ]+\n
• See: https://docs.python.org/3/library/re.html