CMPT 120 Topic: Python strings.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

1 Python Chapter 3 Reading strings and printing. © Samuel Marateck.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 8 More on Strings and Special Methods 1.
Python for Informatics: Exploring Information
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
String and Lists Dr. José M. Reyes Álamo.
Topic: Python Lists – Part 1
CMPT 120 Topic: Python’s building blocks -> More Statements
Topic: Python’s building blocks -> Variables, Values, and Types
Topics Designing a Program Input, Processing, and Output
Topic: Functions – Part 1
Strings CSCI 112: Programming in C.
Topic: Programming Languages and their Evolution + Intro to Scratch
Topic: Iterative Statements – Part 1 -> for loop
CMPT 120 Topic: Python Modules.
Topic: Python’s building blocks -> Statements
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Topic: Conditional Statements – Part 1
Topic: Python’s building blocks -> Variables, Values, and Types
Pamela Moore & Zenia Bahorski
CMPT 120 Topic: Searching – Part 1
Topic: Functions – Part 2
Variables, Expressions, and IO
Topics Introduction to Repetition Structures
Strings Part 1 Taken from notes by Dr. Neil Moore
Introduction to Strings
Introduction to Strings
Learning to Program in Python
Topics Introduction to File Input and Output
Chapter 6 Methods: A Deeper Look
Chapter 8 More on Strings and Special Methods
Chapter 8 More on Strings and Special Methods
Python - Strings.
Data types Numeric types Sequence types float int bool list str
Chapter 8 More on Strings and Special Methods
CSC 221: Introduction to Programming Fall 2018
CEV208 Computer Programming
String and Lists Dr. José M. Reyes Álamo.
Basic String Operations
Introduction to Strings
CS1110 Today: collections.
CISC101 Reminders All assignments are now posted.
Topics Designing a Program Input, Processing, and Output
15-110: Principles of Computing
Topics Basic String Operations String Slicing
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
Introduction to Strings
Topics Basic String Operations String Slicing
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Topic: Iterative Statements – Part 2 -> for loop
Class code for pythonroom.com cchsp2cs
Introduction to Strings
Lecture 7 – Unit 1 – Chatbots Python – For loops + Robustness
CMPT 120 Lecture 10 – Unit 2 – Cryptography and Encryption –
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CMPT 120 Topic: Python strings.
Topics Basic String Operations String Slicing
Presentation transcript:

CMPT 120 Topic: Python strings

Last Lecture Continue learning Python statements (Python’s building blocks) Categories of Statements Operational statements Mathematical/arithmetic operators Order of operations as we practice Step 5 of the software development process -> Testing and Debugging 3 kinds of errors

Learning outcomes At the end of this course, a student is expected to: Create (design) simple algorithms: … Solve problems by designing simple algorithms, e.g., basic calculations, searching in strings and lists, counting, calculating running sums and products Create (design) small size programs using Python: Create programs that search or construct lists and strings

Today’s Menu Python’s building blocks: Python statements Categories of Statements Operational statements Mathematical/arithmetic operators Augmented assignment operators String manipulation operators Function terminology Python strings

Python statements Categories: Assignment statement Input statement Conversion function Output statement Operational statements Mathematical/arithmetic operators String manipulation operators Conditional statement Iterative statement Some of them are built-in function or method Today We’ll see these statements soon!

4. Operational statements String (sequence) manipulation operators: Syntax: <operand> <operator> <operand> Operators: Concatenation operator: + Both operands must be of str data type Repetition operator: * One operand must be of str data type The other operand must be of int data type Format operator: % String formatting Examples: >>> dessertToday = "ice" + "cream" >>> guffaw = "ha" * 3 # OR 3 * "ha" >>> age = 26 >>> message = "Paul is %i years of age." %age >>> print(message) Paul is 26 years of age.

Strings Definition: Sequence of characters 1. How to create a string variable? Answer: Use the name of the string variable For example: 2. How to access a whole string?

String indexing: positive indexing 3. How to access one string character at a time? Answer: Use the index associated with the character as illustrated below: positive indexing-> index: 0 1 2 3 4 5 6 7 8 9 10 11 12 Example: message = "Hello, World!" So if we wish to access The 1st character of the string, we use the index 0 The 2nd character of the string, we use the index 1 etc…

String indexing: positive indexing examples When does the “IndexError: string index out of range” error occur? Careful: Positive index starts at 0

String indexing: negative indexing There is another way we can use to access one string character at a time: negative indexing: Example: message = "Hello, World!" negative indexing-> index: -13 -12 -11-10-9 -8 -7 -6 -5 -4 -3 -2 -1 So if we wish to access The 1st character of the string, we use the index -13 The last character of the string, we use the index -1, etc…

String indexing: negative indexing examples When does the “IndexError: string index out of range” error occur? Careful: Negative index starts at -1, not 0

String slicing (using positive indices) How to access a section (slice) of a string at a time? Answer: use indices to indicate the string slice positive indexing-> index: 0 1 2 3 4 5 6 7 8 9 10 11 12 Example: message = "Hello, World!“ Syntax: <aString>[start : stop : step] start stop step Example: So if we wish to access the string slice "Hello", we use message[0:5]

How does String Slicing works? positive indexing-> index: 0 1 2 3 4 5 6 7 8 9 10 11 12 Example: message = "Hello, World!“ message[0:5] We use index 0 to indicate the start of the string slice Inclusive -> the character at index 0 is included in the string slice We use index 5 to indicate the stop of the string slice Non-inclusive -> the character at index 5 is ***not*** included in the string slice

How does String Slicing works? The Python Interpreter would execute the following as: message[4] where start = 4, stop = ___ and step = ___ message[4:9] where start = 4, stop = 9 and step = ___ message[4:9:2] where start = 4, stop = 9 and step = 2

String Slicing - Direction The direction of slicing dictated by sign of step If step is + positive -> the slicing is done from left to right For example: message[3:11:2] produces the slice -> 'l,Wr' If step is - negative -> the slicing is done from right to left message[-2:-9:-3] produces the slice -> 'do,'

Let’s try! >>> "123456789"[2:8:3] -> >>> "123456789"[2:8:-3] -> >>> "123456789"[-2:-8:-3] -> >>> "123456789"[-2:-8:3] -> >>> "123456789"[8:2:3] -> >>> "123456789"[8:2:-3] -> >>> "123456789"[-8:-2:-3] -> >>> "123456789"[-8:-2:3] ->

String slicing - Examples Note what happens when stop represents an index that is out of range, i.e., the index 25 no longer correspond to a character of the string message since this string only has 13 characters, i.e., from index 0 to index 12. So, Python interprets the index 25 to mean “all the way to the end of the string”. Therefore, it creates a slice of the string message from its character at index 7 all the way to its last character (because the index of this last character is < 25).

String slicing (using negative indices) Example: message = "Hello, World!" negative indexing-> index: -13 -12 -11-10-9 -8 -7 -6 -5 -4 -3 -2 -1

Let’s try!

Strings are immutable! Definition of Immutable: Can we modify a string? For example, let’s try: message[12] = "?" Here is what happened when we tried? Why?

Strings are immutable! But we can create another string that is a modified version of the first string Let’s try this Python program: message = "Hello, World!" question = message[:12] + "?" print("message is still: ", message) print("question is: ", question) What is the output of the above program?

Summary: Strings (sequence) manipulation Operation Name Operator/ function Comment concatenation + Combine strings together repetition * Concatenate a string that is being repeated a number of times indexing [n] Access an element of a string slicing [ : : ] Extract a part of a string length len(aString) Determine the number of characters in a string aString

Built-in functions for strings len( ) is an example of a built-in function for strings in Python Let’s try it on message Notice that the valid range of the indices for the string message is 0 to 12 So … If the length of a string is x then we know that the valid range of the indices for that string is 0 to x-1 If the valid range of the indices for a string is 0 to y then we know that the length of that string is y+1

Other useful built-in functions Method name Use Comment maximum within a string max(aString) Returns the maximum value among the characters in the string aString minimum within a string min(aString) Returns the minimum value among the characters in the string aString We can find more built-in functions at: https://docs.python.org/3.5/library/functions.html

Methods Aside from built-in functions, Python also has methods, which are a specific type of functions that are related to classes Class is a mechanism that allows us to create our own type of objects (variables) Syntax for methods: <string>.<method>(<arguments>) Arguments are not always needed. How do we know if they are? Answer: We must look at a description of the method. dot notation

Methods for strings Methods are called using the dot notation, and are applied to a string that already exist Let’s try this Python program: greetings = "Hello" newGreetings = greetings.upper( ) print(newGreetings) print(greetings) The result is:

Some string methods Method name Use Comment center aString.center(w) Returns a new string, with [the contents of] aString centered in a field of size w count aString.count(item) Returns the number of occurrences of item in aString ljust aString.ljust(w) Returns a new string, with aString left justified in a field of size w rjust aString.rjust(w) Returns a new string, with aString contents right justified in a field of size w upper aString.upper() Returns a new string, with aString contents all in upper cases lower aString.lower() Returns a new string, with aString contents all in lower cases find aString.find(item) Returns the index of the first occurrence of item in aString

A few more string methods title( ) strip( ) rstrip( ) rfind( ) isdigit( ) isalpha( ) isnumeric( ) islower( ) isupper( ) isspace( ) capitalize( ) etc.

More information about string methods You can find a lot more string methods at: https://docs.python.org/3.5/library/stdtypes.html#index-31 Even though we may not talk about all the Python string methods during our lectures, our task, as a Python software developer (i.e., CMPT 120 students), is to become familiar with Python string methods as they will be very useful to us in solving our problems/tasks throughout the semester

Summary Python’s building blocks: Python statements Python strings Categories of Statements Operational statements Mathematical/arithmetic operators Augmented assignment operators String manipulation operators Function terminology Python strings

Next Lecture Python Lists