Get last name from full name by split()
The function can be easily implemented by string method
Code Block |
---|
actor = {"name": "John Cleese", "rank": "awesome"}
def get_last_name():
return actor["name"].split()[1]
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name()) |
Pandas DataFrames
Code Block |
---|
dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221],
"population": [200.4, 143.5, 1252, 1357, 52.98] }
import pandas as pd
brics = pd.DataFrame(dict)
print(brics) |
...
Code Block |
---|
import re
def test_email(your_pattern):
pattern = re.compile(your_pattern)
emails = ["john@example.com", "python-list@python.org", "wha.t.`1an?ug{}ly@email.com"]
for email in emails:
if not re.match(pattern, email):
print("You failed to match %s" % (email))
elif not your_pattern:
print("Forgot to enter a pattern!")
else:
print("Pass")
pattern = r"[a-z0-9]+@[a-z0-9]+\.[a-z0-9]+"
test_email(pattern) |
Exception Handling - try/except block
Code Block |
---|
def do_stuff_with_number(n):
print(n)
def catch_this():
the_list = (1, 2, 3, 4, 5)
for i in range(20):
try:
do_stuff_with_number(the_list[i])
except IndexError: # Raised when accessing a non-existing index of a list
do_stuff_with_number('out of bound - %d' % i)
catch_this()
|
Create word list from a sentence with no duplicate entries
set() removes all the duplicate entries in the array
Code Block |
---|
strings = "my name is Chun Kang and Chun is my name"
r = set(strings.split())
print(r) |
Find overlapped entries from two array
Code Block |
---|
a = set([ "Seoul", "Pusan", "Incheon", "Mokpo" ])
b = set([ "Seoul", "Incheon", "Suwon", "Daejeon", "Gwangjoo", "Taeku"])
print(a.intersection(b))
print(b.intersection(a)) |
The result will be like below
Result |
---|
{ 'Seoul', 'Incheon'}{ 'Seoul', 'Incheon'} |