0% found this document useful (0 votes)
39 views

Slides 3

This document provides a summary of key concepts about strings in Python including: 1) Strings can be defined using single or double quotes and support indexing, slicing, and string methods. 2) String indices start at 0 and can be positive or negative numbers. Slicing allows extracting substrings. 3) Strings support common operations like concatenation, repetition, and various string methods like find, lower, upper. 4) The print function allows formatting output with arguments like sep to control separators and end to control terminators. 5) Escape sequences in strings allow representing special characters like tabs, newlines, and quotes through backslash notation. 6) Formatted string literals with f-strings

Uploaded by

yeunghc519
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)
39 views

Slides 3

This document provides a summary of key concepts about strings in Python including: 1) Strings can be defined using single or double quotes and support indexing, slicing, and string methods. 2) String indices start at 0 and can be positive or negative numbers. Slicing allows extracting substrings. 3) Strings support common operations like concatenation, repetition, and various string methods like find, lower, upper. 4) The print function allows formatting output with arguments like sep to control separators and end to control terminators. 5) Escape sequences in strings allow representing special characters like tabs, newlines, and quotes through backslash notation. 6) Formatted string literals with f-strings

Uploaded by

yeunghc519
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/ 44

Strings

Section 2
Chapter 2

© 2016 Pearson Education, Ltd. All


1
rights reserved.
Quiz 3 Access Code:

• Quizzes will be done at the beginning of each class (10 mins)


• No make up for being late or “technical problems” or other
reasons

© 2016 Pearson Education, Ltd. All rights reserved. 2


Agenda
• String
• String indices and slicing
• String functions and methods
• String concatenation and repetition

• Output
• sep and end arguments in print()
• Escape sequences
• f-strings

• Lab
String Literals
• The most common types of data processed by Python are strings and numbers.

• Sentences, phrases, words, letters of the alphabet, names, telephone numbers,


addresses, and social security numbers are all examples of strings.

• A string literal is a sequence of characters that is treated as a single item.


• Written as a sequence of characters surrounded by either single quotes (') or
double quotes (").

Opening and closing


quotation marks must
be the same type

© 2016 Pearson Education, Ltd. All rights reserved. 4


String Variables
• Variables also can be assigned string values

• Print a string
• Quotation marks not included in display

© 2016 Pearson Education, Ltd. All


5
rights reserved.
Indices and Slices
• Position or index of a character in a string
• Identified with one of the numbers 0, 1, 2, 3, . . . .

© 2016 Pearson Education, Ltd. All


6
rights reserved.
Indices and Slices
• If str1 is a string, then str1[m:n] is the
substring beginning at position m and ending
at position n - 1
• Example “spam & eggs”[2:7]

© 2016 Pearson Education, Ltd. All


7
rights reserved.
find and rfind

If subStr is a string, then str1.find(subStr) is the positive


index of the first appearance of subStr in str1 with the
search beginning at the left side of the string.

The value of str1.rfind(subStr) is the positive index of


the first appearance of subStr in str1 with the search
beginning at the right side of the string.

© 2016 Pearson Education, Ltd. All rights reserved. 8


Negative Indices
• Python allows strings to be indexed by their position with regards to
the right
• Use negative numbers for indices, starting from -1.

© 2016 Pearson Education, Ltd. All


9
rights reserved.
Negative Indices

Notice that the last character “s” is not included.


If str1 is a string, then str1[m:n] is the substring
beginning at position m and ending at position n – 1.
In this case, −1 − 1 = −2.

© 2016 Pearson Education, Ltd. All rights reserved. 10


Default Bounds for Slices

© 2016 Pearson Education, Ltd. All rights reserved. 11


Positive indices start from 0, but not
negative indices… Why?
• Negative Index = Positive Index – Length

• For “e”, its negative index is 7 − 11 = −4

12
© 2016 Pearson Education, Ltd. All rights reserved.
Indexing and Slicing Out of Bounds
• Python does not allow out of bounds indexing for individual
characters of strings
• Does allow out of bounds indices for slices

© 2016 Pearson Education, Ltd. All


13
rights reserved.
Slicing with skips

Str[m:n:s] If str is a string, then str[m:n] is the substring beginning


• s: step(+: forward; - backward) at position m and ending at position n – 1.

© 2016 Pearson Education, Ltd. All rights reserved. 14


String Concatenation
• Two strings can be combined to form a new string
• Consisting of the strings joined together
• Represented by a plus sign

© 2016 Pearson Education, Ltd. All


15
rights reserved.
String Repetition
• Asterisk operator can be used with strings to repeatedly
concatenate a string with itself

© 2016 Pearson Education, Ltd. All


16
rights reserved.
String Functions and Methods

© 2016 Pearson Education, Ltd. All


17
rights reserved.
How to remove unnecessary spaces

© 2016 Pearson Education, Ltd. All rights reserved. 18


Functions vs methods
• A method may alter an object’s state, but Python function usually
only operates on it

• For now, knowing how to apply them is enough.

© 2016 Pearson Education, Ltd. All rights reserved. 19


Chained Methods
• Lines can be combined into a single line said to chain the
two methods
• Executed from left to right

© 2016 Pearson Education, Ltd. All


20
rights reserved.
Line Continuation
• A long statement can be split across two or more lines
• End each line with backslash character ( \ )

• Alternatively, any code enclosed in a pair of parentheses


can span multiple lines.
• This is preferred style for most Python programmers

© 2016 Pearson Education, Ltd. All


21
rights reserved.
Output
Section 3
Chapter 2

© 2016 Pearson Education, Ltd. All


22
rights reserved.
Optional print Argument sep
• Consider statement
print(value0, value1, …, valueN)

• Print function uses string consisting of one space character as the default
separator

• One can change the separator using the sep argument

© 2016 Pearson Education, Ltd. All


23
rights reserved.
Optional print Argument end
• Print statement ends by executing a newline operation.

• Once can change the ending operation with the end argument.

© 2016 Pearson Education, Ltd. All


24
rights reserved.
Escape Sequences: \t
• Escape sequences are short sequences placed in strings
• Instruct cursor or permit some special characters to be printed.
• First character is always a backslash (\).

• \t induces a horizontal tab


• By default, the tab size is eight spaces
• One can control the tab space with “expandtabs”.

© 2016 Pearson Education, Ltd. All


25
rights reserved.
Escape Sequences: \n
• \n induces a newline operation

• Each escape sequence is treated as a single character.

© 2016 Pearson Education, Ltd. All rights reserved. 26


Backslash
• Backslash can be used to print
special characters.

• \’ causes print function to display


single quotation mark

• \” causes print function to display


double quotation mark

• \\ causes print function to display


single backslash

© 2016 Pearson Education, Ltd. All


27
rights reserved.
Justifying Output in a Field
• Example: Program demonstrates methods ljust(w),
rjust(w), and center(w)
• w is the number of columns

© 2016 Pearson Education, Ltd. All


28
rights reserved.
Formated string literals
• No need to worry about object types or adjusting for spaces.

• Note that school and year below are variable names


• Their values are displayed in the output.

• f-strings

© 2016 Pearson Education, Ltd. All rights reserved. 29


f-string

© 2016 Pearson Education, Ltd. All rights reserved. 30


Kahoot
• Go to https://kahoot.it/

• Enter the game PIN as shown on the classroom projector.

• Enter your 8-digit student ID, E.g., 55123456


Do NOT use names.

• Kahoot is separate from the weekly quiz on Canvas. Kahoot


engagement (not merit) will partially determine class participation
scores.

© 2016 Pearson Education, Ltd. All rights reserved. 31


Lab 3

© 2016 Pearson Education, Ltd. All rights reserved. 32


Example A: generate a random letter

© 2016 Pearson Education, Ltd. All rights reserved. 33


The random module
• The random module can help generate random numbers.

© 2016 Pearson Education, Ltd. All rights reserved. 34


Example A: generate a random letter

© 2016 Pearson Education, Ltd. All rights reserved. 35


Example B: n-th letter in the alphabet

Hint: use the method find

© 2016 Pearson Education, Ltd. All rights reserved. 36


Example B: n-th letter in the alphabet

© 2016 Pearson Education, Ltd. All rights reserved. 37


Example C: random password

© 2016 Pearson Education, Ltd. All rights reserved. 38


Example C: random password

© 2016 Pearson Education, Ltd. All rights reserved. 39


Example C: random password

© 2016 Pearson Education, Ltd. All rights reserved. 40


Classwork 3: Caesar Cipher

© 2016 Pearson Education, Ltd. All rights reserved. 41


Classwork 3
#Step 1: Get user inputs.

#Step 2: Find the index of the first letter of the user-entered word in the reference string
"ABCDEFGHIJKLMNOPQRSTUVWXYZ”.

#Step 3: Add the number of shifts to the above index to get the new index.
# Notice that in some cases, the sum would exceed 26. Use the modulo operator %.

#Step 4: Get the encrypted letter based on the new index.

#Repeat the above steps for the remaining letters in the word.

#Step 5: Combine the three letters.

© 2016 Pearson Education, Ltd. All rights reserved. 42


© 2016 Pearson Education, Ltd. All rights reserved. 43
Homework 2
#𝒏
𝑐 𝑐 𝑐 𝟏− 𝟏+𝒓
PV = + !
+ ⋯+ "
=𝒄⋅
1+𝑟 1+𝑟 1+𝑟 𝒓

© 2016 Pearson Education, Ltd. All rights reserved. 44

You might also like