Data Processing and Visulisation with Python
Python Exercise 10
All characters except ‘T’
Write a Python function that takes in a string and prints it out on the screen except for any letter ‘T’ or ‘t’ which should be replaced with ‘*’.
def allButT(m):
m = m.replace('T','*')
print(m.replace('t','*'))
allButT('Tesla is tranferring part of its productivity to China.')
allButT('Tencent announces its new product today.')
Character frequency
Write a Python function frequency(s,c)
to calculate the frequency of charactor c in string s. Then write a Python program to test it.
method 1
def frequency(s,c):
count=0
for letter in s:
if letter == c:
count = count + 1
return count
print(frequency('Zhongnan University of Economics and Law', 'o'))
print(frequency('Happy new year!', 'a'))
method 2
def frequency(s,c):
return s.count(c)
print(frequency('Zhongnan University of Economics and Law', 'o'))
print(frequency('Happy new year!', 'a'))
Frequency of each letter
Write a Python program utilizing the previous function frequency(s, c)
to calculate the frequency of each letter from ‘a’ to ‘z’ in a given string.
method 1
string = "Mother's Day is a celebration honoring the mother of the family, as well as motherhood, maternal bonds, and the influence of mothers in society. It is celebrated on various days in many parts of the world, most commonly in the months of March or May. It complements similar celebrations honoring family members, such as Father's Day, Siblings Day, and Grandparents Day."
string = string.lower()
def frequency(s,c):
n = 0
for i in s:
if i == c:
n += 1
return n
for i in range(ord("a"),ord("z")+1):
j = chr(i)
print(j, ":", frequency(string,j))
method 2
string = "Mother's Day is a celebration honoring the mother of the family, as well as motherhood, maternal bonds, and the influence of mothers in society. It is celebrated on various days in many parts of the world, most commonly in the months of March or May. It complements similar celebrations honoring family members, such as Father's Day, Siblings Day, and Grandparents Day."
string = string.lower()
test = 'abcdefghijklmnopqrstuvwxyz'
for letter in test:
print(letter,":",frequency(string,letter))
Head and tail
Write a Python function headTail(s)
to return a string made of the first 3 and the last 3 characters from a given string. If the given string length is less than 3, then return an empty string.
method 1
def headTail(m):
if len(m)<=3:
new_m = ' '
else:
new_m = m[0:3]+m[-3:]
return new_m
print(headTail('Zhongnan University of Economics and Law'))
print(headTail('Hi'))
print(headTail('abcd'))
Find and replace
Write a Python function findReplace(s)
to find the first appearance of the substring ‘not’ and ‘poor’ from a given string, if ‘not’ is followed by ‘poor’, replace the whole ‘not’…‘poor’ substring with ‘good’. Return the resulting string. Otherwise return the original string.
method 1
def findReplace(s):
a = s.find("not")
b = s.find("poor",a)
if a == -1:
return s
else:
c = s[:a]+"good"+s[b+4:]
return c
print(findReplace('The weather is not so poor.'),findReplace('The weather is poor.'),findReplace('The poor man is not really so poor.'))
method 2
def findReplace(s):
n = s.find('not')
p = s.find('poor',n)
if n != -1 & p != -1:
s = s[:n]+'good.'
return s
print(findReplace('The weather is not so poor.'),findReplace('The weather is poor.'),findReplace('The poor man is not really so poor.'))
method 3
def findReplace(s):
n = s.find('not')
p = s.find('poor')
if n>=0 and p>0 and n<p:
return s.replace(s[n:p+4],'good')
else:
return s
print(findReplace('The weather is not so poor.'),findReplace('The weather is poor.'),findReplace('The poor man is not really so poor.'))
Exchange head and tail
Write a Python function exchangeHeadTail(s)
to transform a given string into a new string where the first and last charactors are exchanged.
def exchangeHeadTail(s):
if len(s) == 1:
return s
else:
c = s[-1]+s[1:-1]+s[0]
return c
print(exchangeHeadTail('good view'))
print(exchangeHeadTail('H'))
HTML tags
Write a Python function to create the HTML string with tags around the word(s).
i.e. write function addTags(t, s)
adds opening tag <t>
at the begining of the string s and the closing tage </t>
at the end of s (t and s should be substituted with proper arguments), then return the result string.
method 1
def addTags(a,s):
b = "<"+a+">"+s+"</"+a+">"
return b
print(addTags('h1', 'Python Tutorial'))
print(addTags('p', 'Python is a very interesting and very powerful language.'))
method 2
def addTags(t,s):
headtag = f"<{t}>"
tailtag = '</' + t +'>'
htmlstr = headtag + s + tailtag
return htmlstr
print(addTags('h1', 'Python Tutorial'))
print(addTags('p', 'Python is a very interesting and very powerful language.'))
Reversion of string
Write a Python function to reverse a given string.
method 1
reverString("Python language")
reverString('Zhongnan University of Economics and Law')
def reverString(s):
c = ""
for i in range(1,len(s)+1):
c = c+s[i*(-1)]
return c
print(reverString("Python language"))
print(reverString('Zhongnan University of Economics and Law'))
method 2
def reverString(s):
b = s[::-1]
return b
print(reverString("Python language"))
print(reverString('Zhongnan University of Economics and Law'))
Caesar encryption
Write a Python function caesarEncryption(s, n)
to convert all characters in string s into lowercase and create a Caesar encryption with shift n, leaving the non-letter characters unchanged, then return the result.
Note:
In cryptography, a Caesar cipher, also known as Caesar’s cipher, the shift cipher, Caesar’s code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3 (i.e. -3), d would be replaced by a, e would become b, c would become z and so on. The method is named after Julius Caesar, who used it in his private correspondence.
method 1
def caesarEncyption(s,n):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
s = s.lower()
newstr = ''
for i in range(len(s)):
key = alphabet.find(s[i])
if n >= 0 :
if key == 26:
newkey = key
elif key > 25 - n:
newkey = key - 26 + n
else:
newkey = key + n
else:
if key == 26:
newkey = key
elif key < -n:
newkey = key + n + 26
else:
newkey = key + n
newstr += alphabet[newkey]
return newstr
print(caesarEncyption('Zhongnan University of Economics and Law', 8))
print(caesarEncyption('hpwvoviv cvqdmzaqbg wn mkwvwuqka ivl tie', -8))
method 2
def caesarEncyption(s,n):
t = s.lower()
s1 = ""
for i in t:
if i == " ":
s1 = s1 + i
else:
if ord(i)+n > 0x7A:
s1 = s1 + chr(ord(i)+n-26)
elif ord(i)+n < 0x61:
s1 = s1 + chr(ord(i)+n+26)
else:
s1 = s1 + chr(ord(i)+n)
return s1
print(caesarEncyption('Zhongnan University of Economics and Law', 8))
print(caesarEncyption('hpwvoviv cvqdmzaqbg wn mkwvwuqka ivl tie', -8))