More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:

Slides:



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

Computer Science 1620 Programming & Problem Solving.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Python Basic Syntax. Basic Syntax - First Program 1 All python files will have extension.py put the following source code in a test.py file. print "Hello,
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
While Loops Indefinite Iteration. Last lesson we looked at definite loops using the ‘For’ statement. The while loop keeps going while some condition is.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Implementation of the Hangman Game in C++
CRE Programming Club - Class 4 Robert Eckstein and Robert Heard.
30/10/ Iteration Loops Do While (condition is true) … Loop.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Last Week if statement print statement input builtin function strings and methods for loop.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 8: Fun with strings.
Susie’s lecture notes are in the presenter’s notes, below the slides Disclaimer: Susie may have made errors in transcription or understanding. If there.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
Python Let’s get started!.
Algorithm Discovery and Design Objectives: Interpret pseudocode Write pseudocode, using the three types of operations: * sequential (steps in order written)
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Iteration. Iteration: Review  If you wanted to display all the numbers from 1 to 1000, you wouldn’t want to do this, would you? Start display 1 display.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Variables and Strings. Variables  When we are writing programs, we will frequently have to remember a value for later use  We will want to give this.
An Introduction to Programming with C++ Sixth Edition Chapter 13 Strings.
CRE Programming Club - Class 4 Robert Eckstein and Robert Heard.
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.
Algorithms and Pseudocode
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
1 Project 7: Looping. Project 7 For this project you will produce two Java programs. The requirements for each program will be described separately on.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Strings … operators Up to now, strings were limited to input and output and rarely used as a variable. A string is a sequence of characters or a sequence.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Selection Using IF THEN ELSE CASE Introducing Loops.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
String and Lists Dr. José M. Reyes Álamo.
Whatcha doin'? Aims: To start using Python. To understand loops.
3.1 Fundamentals of algorithms
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Tuples and Lists.
Introduction To Repetition The for loop
Basic operators - strings
Psuedo Code.
Starter Write a program that asks the user if it is raining today.
Iterations Programming Condition Controlled Loops (WHILE Loop)
Creation, Traversal, Insertion and Removal
Module 4 Loops.
String and Lists Dr. José M. Reyes Álamo.
Programming We have seen various examples of programming languages
Flowcharts and Pseudo Code
15-110: Principles of Computing
String Processing 1 MIS 3406 Department of MIS Fox School of Business
Introduction to Computer Science
Python Strings.
Introduction to Computer Science
Presentation transcript:

More about Strings

String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:  This has now become quite long and difficult to read  The money amount is not formatted as £10.50 as we would want either… 2 of 27

String Formatting  We can improve this by using the string format function:  The numbers in {}’s mark slots in the printed string. They are formatted like this: { : }  The index numbers start at zero (0)  Notice the dot after the closing quote (it can start a new line if necessary) 3 of 27 Yes, I know!

String Formatting There are many format specifiers; here are a couple:  Using a comma as a thousands separator  Applying type-specific formatting formats the fourth value as a floating point number to 2 decimal places. 4 of 27

More about print( )  By default, the print() function adds a space between each comma-separated part a new line after each print  You can change this default behaviour: 5 of 27

Strings as Sequences  What is a sequence? a set of related items that follow each other in a particular order (Oxford English Dictionary)  Strings in Python are sequences of characters  You can refer to a character by using its index Prints: Notice that indexes start at 0 6 of 27

Printing All Characters  How could you print all the characters in phrase?  You wouldn’t want to do it like this…  What do we need if we want to repeat something?  A loop… we need to iterate over the string. How can do this? 7 of 27

Printing All Characters  What if we used a variable for the index?  Does this help you to construct your loop?  What is being repeated, what is the condition, is there any set up?Try this… Set up Repeated What is the condition for repeating?

Printing All Characters: A Loop  What is being repeated?  What is the condition? the index must be less than the length of the string  What is the set up? 9 of 27

Your Turn 1. Write a program to print an input phrase backwards. E.g. if the input phrase is “Hello”, your program should print “olleH” 2. Write a program to count all the instances of the letter “e” in an input phrase Ask the user to enter a phrase Iterate over the string, counting e’s as you go Print this value 10 of 27

Solutions 1. 2.

Strings as Sequences  There are special constructs in Python specifically for sequences  The first we will look at is for, which is another loop  The for loop, iterates over a sequence, automatically assigning each element in turn to the variable; letter in this case.  Notice the use of the keyword, in 12 of 27 This is different from the for loop used in most languages…

While and For… These two programs print the same thing…  Using a for loop:  Using a while loop: 13 of 27

The for Loop  This is the structure of a for loop: for in :  Remember that strings are sequences… An element of a string is a character  Each time around the loop: The automatically gets the next element in the sequence A hidden index moves along by one The loop stops automatically at the end of the sequence 14 of 27

Your Turn Write the pseudo code for this (using the while structure) Then write the code using a) A while loop b) A for loop Write a program to count all the instances of the the letters “t” and the letter “e” in an input phrase Ask the user to enter a phrase Find out how many t’s are in the phrase Find out how many e’s are in the phrase Print this value 15 of 27

Pseudo Code Start get phrase index = 0, t_count = 0, e_count = 0 while index < length of phrase get char from phrase at index position if char == “t” t_count = t_count + 1 else if char == “e” e_count = e_count + 1 end-if index = index + 1 end-while display t_count, e_count Stop

Solution 17 of 27

Solution 18 of 27

Strings are Immutable What does immutable mean? unchanging over time or unable to be changed (Oxford English Dictionary)  When you do this, you are actually creating a new string  This may sound surprising but try this: 19 of 27

Copying a String, missing a letter  Start by copying the string character by character:  Now let’s ignore any g’s in the phrase 20 of 27

The String Module  There are some useful constants in the string module  Notice that the whitespace characters are not printable… 21 of 27

Strings as Sequences: Using in  The keyword in scans a sequence, looking for an element. It returns true if it finds it, false otherwise.  The element can be any size e.g.  You can use this in a loop… What does this do? 22 of 27

Your Turn 1. Write a program that: Asks the user to enter a phrase Counts the number of uppercase characters found in the phrase Prints this value 2. Challenge Task Ask the user to enter a phrase Count the whitespace characters Create new phrase which:  Has a # in place of any digits  Does not include any of the whitespace characters 23 of 27

Solutions Count uppercase characters 24 of 27

Solutions Change the phrase and count whitespace…

String Slicing  As well as getting single items from a sequence, you can get segments. This is called string slicing. [start_inc:end_ex]  Try these…  What are they each doing? 26 of 27

Summary We have looked at  string formatting using the format() function  how you can change the default behaviour of the print function  strings as sequences of characters  how you can iterate over a sequence using while and for  how to use the in keyword  string slicing  Complete MoreStringsExercises.pdf for homework 27 of 27