COMPSCI 101 Principles of Programming Lecture 5 – Manipulating strings, String functions, dot notation.

Slides:



Advertisements
Similar presentations
Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
Advertisements

COMPSCI 101 Principles of Programming Lecture 6 – Getting user input, converting between types, generating random numbers.
Python November 14, Unit 7. Python Hello world, in class.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming.
COMPSCI 101 Principles of Programming
Lecture 2 - Variables, program execution, calculations, print() COMPSCI 101 Principles of Programming.
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
Lists in Python.
IT253: Computer Organization
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Numeric Types, Expressions, and Output ROBERT REAVES.
Lecture 20 – Test revision COMPSCI 101 Principles of Programming.
Input, Output, and Processing
Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.
COMPSCI 101 Principles of Programming Lecture 4 –The type() function, the string type, the len() function, string slices.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Manipulating Text In today’s lesson we will look at: why we might want to pick out parts of text strings some BASIC functions that can be used to chop.
CSE1222: Lecture 2The Ohio State University1. mathExample2.cpp // math example #include using namespace std; int main() { cout
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
COMP 171: Data Types John Barr. Review - What is Computer Science? Problem Solving  Recognizing Patterns  If you can find a pattern in the way you solve.
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Variables and Assignment CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Math, Data Types. Python Math Operations OperationOperator Addition + Subtraction – Multiplication * Division (floating point) / Division (integer) //
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
Lecture 15 – more on lists and for…in loops, the split() function COMPSCI 1 1 Principles of Programming.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python, Class 2 Karsten Hokamp, PhD Genetics TCD, 17/11/2015.
Introduction to Programming Python Lab 3: Arithmetic 22 January PythonLab3 lecture slides.ppt Ping Brennan
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Last of String Manipulation. Programming Challenge Write a program that asks the user for a string and encodes it by the following guidelines: –If the.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
Introduction to Python Lesson 2a Print and Types.
Introduction to Programming
String Manipulation Part 1
String Methods Programming Guides.
COMPSCI 107 Computer Science Fundamentals
Topics Designing a Program Input, Processing, and Output
Introduction to Python
CMSC201 Computer Science I for Majors Lecture 22 – Binary (and More)
Topic: Python’s building blocks -> Statements
Formatting Output.
String Processing Upsorn Praphamontripong CS 1110
CMPT 120 Topic: Python strings.
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
Python - Strings.
Manipulating Text In today’s lesson we will look at:
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Topics Designing a Program Input, Processing, and Output
Variables In today’s lesson we will look at: what a variable is
Chapter 2: Introduction to C++.
CS 1111 Introduction to Programming Spring 2019
Topics Designing a Program Input, Processing, and Output
15-110: Principles of Computing
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
COMPUTER PROGRAMMING SKILLS
Visual Programming COMP-315
CISC101 Reminders Assignment 3 due today.
Class code for pythonroom.com cchsp2cs
CMPT 120 Topic: Python strings.
Presentation transcript:

COMPSCI 101 Principles of Programming Lecture 5 – Manipulating strings, String functions, dot notation

Learning outcomes  At the end of this lecture, students should be able to:  use dot notation when using string functions with string instances  use string functions: upper(), lower(), strip(), find(), rfind()  use the inbuilt functions: min(), max(), round(), abs() CompSci 1012

 What is the output after executing the following code? words = " Prince Charming " print(words[3]) print(words[-5]) print(words[len(words)-1]) print(words[3:6]) print(words[:6]) print(words[6:]) print(words[len(words)-3:]) words = " Prince Charming " print(words[3]) print(words[-5]) print(words[len(words)-1]) print(words[3:6]) print(words[:6]) print(words[6:]) print(words[len(words)-3:]) Recap CompSci 1013

Dot notation  Every object type, as well as storing some data, has some defined functions which can be applied to that particular type of object.  Variables which reference an object are called instances,  e.g., in the following code, greeting is a string instance and number is an instance of type int.  In order to apply a function to an object we use dot notation, i.e., the variable name, followed by a dot, followed by the function name. greeting = "Hello World" number = 234 greeting = "Hello World" number = 234 CompSci 1014 instance_name. function_name(…) Note that we use parentheses after the function name.

String functions  String instances have many functions which can be applied to them.  Such as upper(), lower(), find(), strip(), isalpha(), isdigit(), rfind(), split() ….  In this lecture we will look at a few of these functions. CompSci 1015

String functions – upper(), lower()  The upper() function returns a new string object with all the characters converted to upper case.  The lower() function returns a new string object with all the characters converted to lower case.  For example, Hello World hello world HELLO WORLD greeting = "Hello World" greeting_lower = greeting.lower() greeting_upper = greeting.upper() print(greeting) print(greeting_lower) print(greeting_upper) greeting = "Hello World" greeting_lower = greeting.lower() greeting_upper = greeting.upper() print(greeting) print(greeting_lower) print(greeting_upper) CompSci 1016 Notice that there are three string objects DEMO Example01.py

String functions – find()  The find() function is used to look for the position or index number of the first occurrence (from the left) of some characters.  If the characters are found, the find() function returns the index number, otherwise the function returns -1.  For example, 5 7 H 0 e 1 l 2 l 3 o 45 W 6 o 7 r 8 l 9 d 10 greeting position1 = greeting.find(" ") position2 = greeting.find("z") position3 = greeting.find("orl") print(position1) print(position2) print(position3) position1 = greeting.find(" ") position2 = greeting.find("z") position3 = greeting.find("orl") print(position1) print(position2) print(position3) CompSci 1017 DEMO Example01.py

String functions – rfind()  The rfind() function is used to look for the position of the last occurrence (from the right) of some characters.  If the characters are found, the rfind() function returns the index number, otherwise the function returns -1.  For example, H 0 e 1 l 2 l 3 o 45 W 6 o 7 r 8 l 9 d 10 greeting position1 = greeting.find("o") position2 = greeting.rfind("o") position3 = greeting.rfind("orl") position4 = greeting.rfind("lro") print(position1)... position1 = greeting.find("o") position2 = greeting.rfind("o") position3 = greeting.rfind("orl") position4 = greeting.rfind("lro") print(position1) CompSci 1018 DEMO Example01.py From left… Index : 4 From right… Index 7

String functions – strip()  The strip() function function removes all white space from the beginning and end of the string.  Note: it does not remove spaces from inside the string.  For example, letters1 = " H e l l o oooo " letters2 = letters1.strip() length1 = len(letters1) length2 = len(letters2) print(length1, length2) print(letters1, "*") print(letters2, "*") letters1 = " H e l l o oooo " letters2 = letters1.strip() length1 = len(letters1) length2 = len(letters2) print(length1, length2) print(letters1, "*") print(letters2, "*") H e l l o oooo * CompSci 1019 DEMO Example01.py Spaces are removed from the end Spaces are removed from the beginning

Exercise 1  What is the output after executing the following code? CompSci s = "Programming is fun" print(s.find('ram')) print(s.find('rom')) print(s.find('m')) print(s.rfind('m')) s = "Programming is fun" print(s.find('ram')) print(s.find('rom')) print(s.find('m')) print(s.rfind('m'))

Programming Exercise 1  Complete the following program so that it prints the initial from the first name followed by a full stop, a space and followed by the surname. Assume the full name is always two names separated by one space. W. Auden full_name = "Wystan Auden" initialled_name = first_letter + ". " + last_name print(initialled_name) full_name = "Wystan Auden" initialled_name = first_letter + ". " + last_name print(initialled_name) CompSci 10111

Algorithm Find the position of the spaceGet the first letterConvert it to upper caseGet the last name (position_blank + 1 … end)Print the result (first_letter + ". " + last_name) CompSci W 0 y 1 s 2 t 3 a 45 6 A 7 u 8 d 9 e 10 position_blank n 11 n full_name[0] [position_blank + 1:] W. Auden

Common Python inbuilt functions  min() is an inbuilt function which can be used to find the smallest number from a comma separated set of numbers  max() is the inbuilt function which can be used to find the largest number from a comma separated set of numbers, e.g., num1 = 32 num2 = 16 smallest = min(num1, num2) print(smallest) smallest = min(32.7, 56.4, 3, -1.1, 56.99, -1.2) print(smallest) largest = max(num1, num2) print(largest) largest = max(32.7, 56.4, 3, -1.1, 56.99, -1.2) print(largest) num1 = 32 num2 = 16 smallest = min(num1, num2) print(smallest) smallest = min(32.7, 56.4, 3, -1.1, 56.99, -1.2) print(smallest) largest = max(num1, num2) print(largest) largest = max(32.7, 56.4, 3, -1.1, 56.99, -1.2) print(largest) CompSci DEMO Example02.py

Common Python inbuilt functions  The function, round(), is used to round numbers to the closest whole number (or rounded to a number of digits after the decimal point) e.g.,  round(number[, ndigits])  Return the floating point value number rounded to ndigits digits after the decimal point. num1 = num2 = num3 = print(round(num1)) print(round(num2)) print(round(num3)) num1 = num2 = num3 = print(round(num1)) print(round(num2)) print(round(num3)) CompSci print(round(num1, 2)) print(round(num2, 3)) print(round(num1, 2)) print(round(num2, 3)) Rounded to 2 digits after the decimal point Rounded to 3 digits after the decimal point DEMO Example02.py

Common Python inbuilt functions  The function, abs(), is used to get the absolute value (the magnitude) of a number (int or float), e.g., num1 = 32 num2 = -32 num3 = abs(num2 - num1) print(abs(num1)) print(abs(num2)) print(num3) num1 = 32 num2 = -32 num3 = abs(num2 - num1) print(abs(num1)) print(abs(num2)) print(num3) CompSci DEMO Example02.py

round() – Unexpected Result  Sometimes the round() function seems to give an unexpected result e.g.,  If two multiples are equally close, rounding is done toward the even choice num1 = 1.5 num2 = 2.5 num3 = 3.5 print(round(num1)) print(round(num2)) print(round(num3)) num1 = 1.5 num2 = 2.5 num3 = 3.5 print(round(num1)) print(round(num2)) print(round(num3)) CompSci surprising result

Exercise 2  What is the output after executing the following code? CompSci print(min(3, 5, 1, 7, 4)) print(max(3, 5, 1, 7, 4)) print(round(3.52)) print(round(6.5)) print(round(7.5)) print(min(3, 5, 1, 7, 4)) print(max(3, 5, 1, 7, 4)) print(round(3.52)) print(round(6.5)) print(round(7.5))

Programming Exercise 2  Complete the following program so that it prints the total tax rounded to a whole number.  The first $14000 is not taxed. The next amount up to $38000 is taxed at 24% and the rest is taxed at 34%. salary = no_tax_boundary = rate1_boundary = rate1 = 0.24 rate2 = 0.34 print("===============================") print("Total tax: $", total_tax, sep = "") print("===============================") salary = no_tax_boundary = rate1_boundary = rate1 = 0.24 rate2 = 0.34 print("===============================") print("Total tax: $", total_tax, sep = "") print("===============================") Salary: $54000 Amount to be taxed at: 24.0%: $24000 Tax at rate1: $ Amount to be taxed at: 34.0%: $16000 Tax at rate2: $ =============================== Total tax: $11200 =============================== CompSci 10118

Cases: CompSci Salary: $12000 $12000 Rate= 24% Rate= 34% Rate= 0% $14000 Rate= 24% Rate= 34% Rate= 0% Salary: $20000 $6000 $14000 Rate= 24% Rate= 34% Rate= 0% Salary: $54000 $24000 $16000 taxable2 taxable1

Algorithm Calculate taxable2 Zero or salary - rate1_boundary Calculate taxable1 Zero or rate1_boundary - no_tax_boundary Calculate the tax amount on taxable1Calculate the tax amount on taxable2Calculate the total tax CompSci 10120

Summary  In Python:  use dot notation when using string functions with string instances  the string functions: upper(), lower(), strip(), find(), rfind() can be used with string instances  the inbuilt functions: min(), max(), round() can be used CompSci 10121