0% found this document useful (0 votes)
9 views22 pages

MA1008 Week 6 (Strings)

The document is a tutorial on strings in Python, covering various string manipulations and methods. It includes exercises on printing characters, string formatting, and ASCII values, as well as programming tasks related to string encryption and validation of variable names. Additionally, it provides examples of using f-strings and formatting output for mathematical calculations.

Uploaded by

Ananya Jayanty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views22 pages

MA1008 Week 6 (Strings)

The document is a tutorial on strings in Python, covering various string manipulations and methods. It includes exercises on printing characters, string formatting, and ASCII values, as well as programming tasks related to string encryption and validation of variable names. Additionally, it provides examples of using f-strings and formatting output for mathematical calculations.

Uploaded by

Ananya Jayanty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Introduction to Computational Thinking

MA1008
Tutorial Strings
Week 6
Question 1
Human 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
Computer 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
Text I n t r o d u c t i o n t o C o m p u t a t i o n a l T h i n k i n g

1. Given the string "Introduction to Computational Thinking", write an expression to


i. print the first character
S=“Introduction to Computational Thinking”
print(S[0])
ii.print the last character, assuming you don’t know the string length
print(S[-1])
iii.print the last character using len()
print(S[len(S)-1])
iv.print the first word
print(S[0:12])
v. print the 4th to 14th characters.
print(S[3:14])
vi. print the 4th to 14th characters in the reverse order
print(S[13:2:-1])
vii.print every alternate character starting from the second
print(S[1::2])
Question 2
Study the Python methods associated with string, and write down the expressions for
doing the following, given the string "it's a beautiful day."
i.Capitalize the first word
S1 = "it's a beautiful day."
S2 = S1.capitalize() #returns the string with the first “i” capitalized.
ii.Capitalize each word
S2 = S1.title()
iii.Convert the whole string to upper case
S2 = S1.upper()
iv.Remove all the spaces
S2 = S1.replace(" ", "")
v. Count the number of a specific character in the string
S1.count("a") #counts the number of “a” in the string, and should return 3.
About f-strings
F-strings is a feature for formatting strings in an intuitive manner.
Here, f-string is used within a print function. Starting with an f prefix,
followed by the first quotation mark. Curly brackets are used to indicate
the insertion of a variable into the overall string.

pet = "cat"
age = 10
print(f"My {pet} is {age} years old.")

The alternative is to type out print("My", pet, "is", age, "years old.").
That is a little more cumbersome.
The f-string’s benefit is more obvious when formatting the printing of
numbers.
import math
print(math.pi)
print(f"The value of pi to 2 decimal places is: {math.pi:.2f}")
Question 3
Write down the output of the following statements. Mark the spaces with a .
for fahr in range (32, 200, 50):
cels = (fahr-32)*5/9
print(f"{fahr:>4d} Fahrenheit = {cels:<6.2f} Celsius")
Print as float
Right justify
2 decimal places
4 spaces
6 spaces
Print as integer
Left justify
32 Fahrenheit=0.00Celsius
82 Fahrenheit = 27.78Celsius
132 Fahrenheit = 55.56Celsius
182 Fahrenheit = 83.33Celsius

Take note that parameters like :>4d and :<6.2f are optional. They do (usually) cause syntax errors when not
included. You can try the line print(f"{fahr} Fahrenheit = {cels} Celsius") to see the difference.
Question 4
4. Given the assignment
S = "I am testing my program"
What is the outcome of the following statements?

Human 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Computer 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Text I a m t e s t i n g m y p r o g r a m

i. S[0] = "J" Error. More specifically, type error because string is not mutable.
ii. print(S)
I am testing my program
iii. print(S[::3])
Imei oa ( represents the space character)
iv. print(S[12:4:-1])
gnitset
Question 5
5. What are printed by the following expressions:
i. print("Nanyang"*3)
NanyangNanyangNanyang
ii. print("Nanyang"*3.0)
Error. Can’t multiply string by non-integer types.
iii. print("Nanyang"*-3)
An empty string.Same result if “Nanyang”*0.
iv. print("Nanyang" + "Technological" + "University")
NanyangTechnologicalUniversity
v. print("Nanyang" - "N")
Error. “-”is undefined for strings.
Question 6
6. Write down what is printed by the
code below once you give the input (use
your own input).

string = input("Enter a string: ")


y = 0
for c in string:
print(y, c)
y += 1

It prints every letter (on a new line),


preceded by its index.
Question 7
7. Without using division, write a statement that would store the last digit
of an integer as an integer.

To clarify, the question is asking how we can for example store the number 5
in the string “12345”, as an integer.

Hints: 1) How to reference the last character of a string?

2)How to cast that character into an integer?

lastDigit = int(str(12345)[-1])
Programming Strings
Question 1
1. Write a program that would prompt for a string and then print the
ASCII value of each character in the string.

string = input("Enter a string: ")


for c in string:
print(c, ord(c))
14
Question 2
2. Write a program that prints the multiplication table between 0 to 12
in a neat table.
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144

for i in range(1, 13):


for j in range(1, 13):
print(f"{i*j:>4d}", end = "")
print()
Question 3
3. Write a program that reads in a word and prints True if the word
contains all the vowels and False otherwise.

word = input("Enter a word: ")


if ("a" in word or "A" in word) and ("e" in word or "E" in word) \
and ("i" in word or "I" in word) and ("o" in word or "O" in word) \
and ("u" in word or "U" in word):
print(True)
else:
print(False)
Question 4
4. Write a program that prompts for a sentence and then outputs the number of (1)
upper case letters, (2) lower case letters, (3) digits, and (4) other characters.

input_string = input('Enter a sentence: ')


digits, upper, lower, others = 0, 0, 0, 0
for c in input_string:
if c.isdigit(): This question introduces you to the functions isupper(),
digits += 1 islower() and isdigit().
elif c.isupper():
For example, given a string S. When isupper()is used in
upper += 1 the format of S.isupper(), a Boolean result is created
elif c.islower(): based on whether all characters in S are uppercase.
lower += 1
In this question, you do not have to supply the printout in
else:
the f-string format. But it is good for you to practice.
others += 1
print("Digits Upper Lower Others")
print(f"{digits:^6d} {upper:^6d} {lower:^6d} {others:^6d}")
Question 5
5. An encryption system uses the following rules:
(1) A letter, upper case or lower case, is replaced by a
letter of the same case five places up the alphabet. If
this falls past the end of the alphabets, it is wrapped
round to the beginning. So “b” becomes “g”, and “y”
becomes “d”.
(2) A digit is replaced by a digit larger by 3. If this is
greater than 9, it is wrapped round to the other end. So 3
becomes 6, and 8 becomes 1.
(3) All other characters remain unchanged.

Write a program that reads in a string of characters and


produces the encrypted string according to the above
rules.
Question 5
in_str = input("Enter s string: ")
out_str = ""

for c in in_str: #for loop that has as many iterations as the number of chars in in_str. c is the char at that iteration
if c.isalpha():
new_c = ord(c) + 5
if c.isupper() and new_c > ord("Z"): # upper case letter that needs to wraparound
new_c = new_c - ord("Z") + ord("A") – 1 #formula to wraparound
elif c.islower() and new_c > ord("z"): #lowercase letter that needs to wraparound
new_c = new_c - ord("z") + ord("a") – 1 #formula to wraparound
elif c.isdigit(): # it's a digit
new_c = ord(c) + 3
if new_c > ord("9"): #digit that needs to wraparound
new_c = new_c - ord("9") + ord("0") – 1 #formula to wraparound
else:
new_c = ord(c) #no change

out_str = out_str + chr(new_c) #chr() is the function to convert Ascii value back to character.

print("The encrypted string is : ", out_str)


Question 6
6. Write a program to read in a Python variable and print "Valid"
if it is a valid Python variable and "Invalid" otherwise. For this
exercise, you can assume that Python keywords do not exist, i.e. you
don’t have to check against them.

var = input("Enter a variable: ")


valid = "Invalid"

if var[0].isalpha() or var[0] == "_": # check first character


valid = "Valid"
for c in var: # check each index of the string one by one
if not (c.isdigit() or c.isalpha() or c == '_'):
valid = "Invalid"

print(f"Variable {var} is {valid}.")


Question 6
The answer can be further refined with some small additions.
var = input("Enter a variable: ")
valid = "Invalid"

if var[0].isalpha() or var[0] == "_": # check first character


valid = "Valid"
for c in var[1:]: # check each index, starting at the 2nd.
if not (c.isdigit() or c.isalpha() or c == '_'):
valid = "Invalid"
break #once an invalid character is encountered, no need to check further

print(f"Variable {var} is {valid}.")


Question 7
7. Write a program to calculate the circumference and area of a
circle given the radius, and output the results in the format as in
this example:
Radius of circle = 10.00, circumference = 62.83, area = 314.16
Note that all the numbers have a fixed number of decimal places, and
no redundant spaces before the number.

import math

radius = float(input("Enter the radius: "))

area = math.pi*radius*radius
circ = math.pi*radius*2

print(f"Radius of circle = {radius:.2f}, circumference = {circ:.2f}, \


area = {area:.2f}")

You might also like