Adapted from slides by Marty Stepp and Stuart Reges

Slides:



Advertisements
Similar presentations
Java Programming Strings Chapter 7.
Advertisements

BUILDING JAVA PROGRAMS CHAPTER 6.4 FILE OUTPUT. 22 PrintStream : An object in the java.io package that lets you print output to a destination such as.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Week 4 Strings, if/else, return, user input Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Week 4 gur zntvp jbeqf ner fdhrnzvfu bffvsentr Strings, if/else, return, user input Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Strings, if/else, return, user input
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
1 Text Processing. 2 Type char char : A primitive type representing single characters. –A String is stored internally as an array of char String s = "Ali.
Objects and Classes; Strings. 2 Classes and objects class: A program entity that represents either 1.A program / module, or 2.A type of objects* –A class.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python, Class 2 Karsten Hokamp, PhD Genetics TCD, 17/11/2015.
If/else, return, user input, strings
CHAPTER 6 GC Strings. THE CLASS STRING  Contains operations to manipulate strings.  String:  Sequence of zero or more characters.  Enclosed.
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, 4.3.
Adapted from slides by Marty Stepp and Stuart Reges
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Building Java Programs
Building Java Programs
Building Java Programs
CSc 110, Autumn 2017 Lecture 13: Cumulative Sum and Boolean Logic
CSc 110, Autumn 2017 Lecture 15: Strings and Fencepost Loops
Building Java Programs
Building Java Programs Chapter 4
Lecture 8: The String class
Lecture 4: Expressions and Variables
Building Java Programs
Chapter 6 GC 101 Strings.
Adapted from slides by Marty Stepp and Stuart Reges
Building Java Programs Chapter 4.3
Strings string: An object storing a sequence of text characters.
CSc 110, Autumn 2016 Lecture 12: Advanced if/else; Cumulative sum
CSc 110, Autumn 2017 Lecture 5: The for Loop and user input
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
CSc 110, Spring 2017 Lecture 11: while Loops, Fencepost Loops, and Sentinel Loops Adapted from slides by Marty Stepp and Stuart Reges.
CS 106A, Lecture 9 Problem-Solving with Strings
Week 4 gur zntvp jbeqf ner fdhrnzvfu bffvsentr
CSc 110, Spring 2017 Lecture 9: Advanced if/else; Cumulative sum
CSc 110, Spring 2017 Lecture 5: Constants and Parameters
CSc 110, Spring 2018 Lecture 9: Parameters, Graphics and Random
Building Java Programs
Lecture 3: Expressions and Variables
CSc 110, Autumn 2016 Lecture 5: Loop Figures and Constants
Topic 12 more if/else, cumulative algorithms, printf
Adapted from slides by Marty Stepp and Stuart Reges
CSc 110, Spring 2018 Lecture 14: Booleans and Strings
Building Java Programs
CSc 110, Autumn 2016 Lecture 10: Advanced if/else; Cumulative sum
CSC 221: Introduction to Programming Fall 2018
CEV208 Computer Programming
CSc 110, Spring 2018 Lecture 7: input and Constants
CSc 110, Spring 2018 Lecture 5: The for Loop and user input
Building Java Programs
Adapted from slides by Marty Stepp and Stuart Reges
CSc 110, Spring 2018 Lecture 13: Cumulative Sum and Boolean Logic
CSc 110, Spring 2018 Lecture 5: Loop Figures and Constants
Basic String Operations
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 14: Strings and Recursion AP Computer Science Principles
Building Java Programs
Using Objects (continued)
Lecture 4: Expressions and Variables
Building Java Programs
Introduction to Computer Science
Building Java Programs
Strings string: An object storing a sequence of text characters.
Presentation transcript:

Adapted from slides by Marty Stepp and Stuart Reges CSc 110, Autumn 2016 Lecture 11: Strings Adapted from slides by Marty Stepp and Stuart Reges

Strings string: a type that stores a sequence of text characters. name = "text" name = expression Examples: name = "Daffy Duck" x = 3 y = 5 point = "(" + str(x) + ", " + str(y) + ")"

Indexes Characters of a string are numbered with 0-based indexes: name = "Ultimate" First character's index : 0 Last character's index : 1 less than the string's length index 1 2 3 4 5 6 7 -8 -7 -6 -5 -4 -3 -2 -1 character U l t i m a e

Accessing characters You can access a character with string[index]: name = "Merlin" print(name[0]) Output: M

Accessing substrings Syntax: part = string[start:stop] Example: s = "Merlin" mid = [1:3] # er If you want to start at the beginning you can leave off start mid = [:3] # Mer If you want to start at the end you can leave off the stop mid = [1:] # erlin

String methods These methods are called using the dot notation below: Method name Description find(str) index where the start of the given string appears in this string (-1 if not found) substring(index1, index2) or substring(index1) the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string lower() a new string with all lowercase letters upper() a new string with all uppercase letters These methods are called using the dot notation below: starz = "Biles & Manuel" print(starz.lower()) # biles & manuel

String method examples # index 012345678901 s1 = "Allison Obourn" s2 = "Merlin The Cat" print(s1.find("o")) # 5 print(s2.lower()) # "merlin the cat" Given the following string: # index 012345678901234567890123 book = "Building Python Programs" How would you extract the word "Python" ?

Modifying strings String operations and functions like lowercase build and return a new string, rather than modifying the current string. s = "Aceyalone" s.upper() print(s) # Aceyalone To modify a variable's value, you must reassign it: s = s.upper() print(s) # ACEYALONE

Name border Prompt the user for full name ALLISON LLISON LISON ISON SON ON N A AL ALL ALLI ALLIS ALLISO OBOURN BOURN OURN URN RN O OB OBO OBOU OBOUR Prompt the user for full name Draw out the pattern to the left This should be resizable. Size 1 is shown and size 2 would have the first name twice followed by last name twice

Other String operations - length Syntax: length = len(string) Example: s = "Merlin" count = len(s) # 6

Looping through a string The for loop through a string using range: major = "CSc"; for letter in range(0, len(major)): print(major[letter:letter + 1]) You can also use a for loop to print or examine each character without range. for letter in major: print(letter) Output: C S c

Strings question Write a program that reads two people's first names and suggests a name for their child Example Output: Parent 1 first name? Danielle Parent 2 first name? John Child Gender? f Suggested baby name: JODANI Child Gender? Male Suggested baby name: DANIJO

String tests Method Description startswith(str) whether one contains other's characters at start endswith(str) whether one contains other's characters at end name = "Voldermort" if(name.startswith("Vol")): print("He who must not be named") The in keyword can be used to test if a string contains another string. example: "er" in name # true

String question A Caesar cipher is a simple encryption where a message is encoded by shifting each letter by a given amount. e.g. with a shift of 3, A  D, H  K, X  A, and Z  C Write a program that reads a message from the user and performs a Caesar cipher on its letters: Your secret message: Brad thinks Angelina is cute Your secret key: 3 The encoded message: eudg wklqnv dqjholqd lv fxwh

Strings and ints All char values are assigned numbers internally by the computer, called ASCII values. Examples: 'A' is 65, 'B' is 66, ' ' is 32 'a' is 97, 'b' is 98, '*' is 42 One character long Strings and ints can be converted to each other ord('a') is 97, chr(103) is 'g' This is useful because you can do the following: chr(ord('a' + 2)) is 'c'

Strings answer # This program reads a message and a secret key from the user and # encrypts the message using a Caesar cipher, shifting each letter. def main(): message = input("Your secret message: ") message = message.lower() key = int(input("Your secret key: ")) encode(message, key) # This method encodes the given text string using a Caesar # cipher, shifting each letter by the given number of places. def encode(text, shift): print("The encoded message: ") for letter in text: # shift only letters (leave other characters alone) if (letter >= 'a' and letter <= 'z'): letter = chr(ord(letter) + shift) # may need to wrap around if (letter > 'z'): letter = chr(ord(letter) - 26) elif (letter < 'a'): letter = chr(ord(letter) + 26) print(letter, end='') print()

format

Formatting text with format print("format string".format(parameters)) A format string can contain placeholders to insert parameters: {:d} integer {:f} real number {:s} string these placeholders are used instead of + concatenation Example: x = 3; y = -17; print("x is {:d} and y is {:d}!".format(x, y)) # x is 3 and y is -17!

format width {:Wd} integer, W characters wide ... for i in range(1, 4): for j in range(1, 11): print("{:4d}".format(i * j), end='') print() # to end the line Output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30

format precision {:.Df} real number, rounded to D digits after decimal {:W.Df} real number, W chars wide, D digits after decimal gpa = 3.253764 print("your GPA is {:.1f}".format(gpa)) print("more precisely: {:8.3f}".format(gpa)) Output: your GPA is 3.3 more precisely: 3.254 3 8

format question Modify our Receipt program to better format its output. Display results in the format below, with 2 digits after . Example log of execution: How many people ate? 4 Person #1: How much did your dinner cost? 20.00 Person #2: How much did your dinner cost? 15 Person #3: How much did your dinner cost? 25.0 Person #4: How much did your dinner cost? 10.00 Subtotal: $70.00 Tax: $5.60 Tip: $10.50 Total: $86.10

format answer (partial) ... # Calculates total owed, assuming 8% tax and 15% tip def results(subtotal): tax = subtotal * .08 tip = subtotal * .15 total = subtotal + tax + tip # print("Subtotal: $" + str(subtotal)) # print("Tax: $" + str(tax)) # print("Tip: $" + str(tip)) # print("Total: $" + str(total)) print("Subtotal: ${:.2f}".format(subtotal)) print("Tax: ${:.2f}".format(tax)) print("Tip: ${:.2f}".format(tip)} print("Total: ${:.2f}".format(total))