Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Chapter 4 Working with Strings. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Sequence of characters.
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Computing with Strings CSC 161: The Art of Programming Prof. Henry Kautz 9/16/2009.
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.
Introduction to Python
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.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Python for Informatics: Exploring Information
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Strings CS303E: Elements of Computers and Programming.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
12/9/2010 Course A201: Introduction to Programming.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 5 Strings CSC1310 Fall Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.
Chapter 4 Working with Strings. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Sequence of characters.
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.
More Strings CS303E: Elements of Computers and Programming.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Strings The Basics. Strings a collection data type can refer to a string variable as one variable or as many different components (characters) string.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
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.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
Input, Output and Variables GCSE Computer Science – Python.
Topics Designing a Program Input, Processing, and Output
CSc 120 Introduction to Computer Programing II Adapted from slides by
CMPT 120 Topic: Python strings.
Variables, Expressions, and IO
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Strings
Introduction to Strings
CHAPTER THREE Sequences.
Python - Strings.
Data types Numeric types Sequence types float int bool list str
Chapter 8 More on Strings and Special Methods
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Basic String Operations
PROGRAMMING IN HASKELL
Introduction to Strings
CHAPTER 3: String And Numeric Data In Python
functions: argument, return value
Topics Designing a Program Input, Processing, and Output
Intro to Computer Science CS1510 Dr. Sarah Diesburg
15-110: Principles of Computing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Basic String Operations String Slicing
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
Introduction to Strings
Python Review
Python Strings.
Topics Basic String Operations String Slicing
By Himanshi dixit 11th ’B’
Introduction to Strings
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CMPT 120 Topic: Python strings.
Topics Basic String Operations String Slicing
Presentation transcript:

Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1

If you have the old book! This chapter is the one with most differences between: – the new and the old book, – 3.2 and 2.7 Python – The differences are in the string formatting that we show at the end of the slides. 2

Overview String objects: – What are they? – How to create them? – They are immutable. Element/character access Comparing strings: lexicographic order String operators: +, * Converting str objects to and from other types String methods – Find, index, in The ASCII code Strings with special characters String formatting 3

String objects Words, sentences and whole phrases can be stored as string objects. Creating strings – Using single or double quotes: 'These', " are ", """string objects. """ Double quotes are better than single : “ Bob’s” vs ‘Bob’s’ The triple quotes preserve formatting (new lines). You can use them for longer comments. – Using the str constructor: str(123), str([1,2,3]) String operators: +, * – Strings can be concatenated together with + >>> 'This' + ' is a ' + ' new string.' – String repetitions: >>> ' apple ' * 3 >>> ' apple ' * 0 4

Strings: element access Individual elements: >>> my_str = "Lovely" >>> my_str[0] >>> my_str[5] Slicing: >>> my_str[::2] # a string formed from every other letter >>> my_str[::-1] # a copy of the string in reversed order Iterate over a string with a for loop len function gives the length of a string >>> len(my_str) 5

The in Operator >>> a = [1, 2, 3] >>> 2 in a True >>> 5 in a False >>> vowels = "aeiou" >>> "a" in vowels True >>> "k" in vowels False 6 The in operator works for lists and strings. Syntax: element in container Returns true if the element appears in the container, false otherwise.

upper and lower 7 >>> vowels = "aeiou" >>> b = vowels.upper() >>> vowels 'aeiou' >>> b 'AEIOU' >>> a = " New York City " >>> b = a.lower() >>> b 'new york city' The string.upper() method returns a new string where all letters are upper case. The string.lower() method returns a new string where all letters are lower case. Note: upper() and lower() do not modify the original string, they just create a new string. Should be obvious, because strings cannot be modified.

index and find 8 >>> my_str = "this is crazy" >>> my_str.index("is") 2 # is this correct? >>> my_str.index("q") error >>> my_str.find("is") 2 >>> my_str.find("q") The my_list.index(X) method returns the first position where X occurs in the string. Gives an error if X is not in my_list. The my_string.find(X) method returns the first position where X occurs in the string. X can be a single letter or more letters. Returns -1 if X is not found.

String Comparisons >>> my_strings = ["abc", "ABC", "Abc", "abcd", "acd", "a","A", "c","C"] >>> my_strings ['abc', 'ABC', 'Abc', 'abcd', 'acd', 'a', 'A', 'c', 'C'] >>> my_strings.sort() >>> my_strings ['A', 'ABC', 'Abc', 'C', 'a', 'abc', 'abcd', 'acd', 'c'] Python uses the lexicographic (dictionary) order for strings. Capital letters are always before lower case letters. 9

String Comparisons It is easy to verify the order that Python uses, by trying out different pairs of strings. >>> "hello" < "goodbye" False >>> "Hello" < "goodbye" True >>> "ab" > "abc" False 10

String Comparisons >>> "123" < "abc" True >>> "123" < "ABC" True Numbers come before letters. Comparing strings of different lengths. – Any prefix of a string is smaller than the string itself. >>> "ab" > "abc" False 11

Strings Cannot Change >>> a = "Munday" >>> a[1] = 'o' Traceback (most recent call last): File " ", line 1, in a[1] = 'o' TypeError: 'str' object does not support item assignment 12

If You Must Change a String… You cannot, but you can make your variable equal to another string that is what you want. Example: >>> my_string = "Munday" – my_string contains a value that we want to correct. >>> my_string = "Monday" – We just assign to variable my_string a new string value, that is what we want. 13

For More Subtle String Changes… Suppose that we want a program that: – Gets a string from the user. – Replaces the third letter of that string with the letter A. – Prints out the modified string. 14

For More Subtle String Changes… Strategy: – convert string to list of characters – do any manipulations we want to the list (since lists can change) – convert list of characters back to a string Using a loop. Using the join method for strings. – joining_string.join(list_of_strings) – >>> " - ".join([1,2,3]) 15

Write a program that: – Gets a string from the user. – Modifies that string so that position 3 is an A. – Prints the modified string. 16 An Example

An Example: with loop my_string = input("please enter a string: ") if (len(my_string) >= 3): # convert string to list, make the desired change (change third letter to "A") my_list = list(my_string) my_list[2] = "A"; # create a string out of the characters in the list new_string = "" for character in my_list: new_string = new_string + character my_string = new_string # assign the my_string variable to the new string object print("the modified string is ", my_string) 17

An Example: with join my_string = input("please enter a string: ") if (len(my_string) >= 3): # convert string to list, make the desired change (change third letter to "A") my_list = list(my_string) my_list[2] = "A"; # create a string out of the characters in the list new_string = "".join(my_list) my_string = new_string print("the modified string is ", my_string) 18

An Example: with slicing and + my_string = input("please enter a string: ") my_string = my_string[0:2] + "A" + my_string[3:] print("the modified string is ", my_string) 19

Converting Other Types to Strings 20 >>> a = 2012 >>> b = str(a) >>> b '2012' >>> a = ['h', 'e', 'l', 'l', 'o'] >>> b = str(a) >>> b "['h', 'e', 'l', 'l', 'o']" >>> "".join(a) 'hello' >>>" ".join(a) 'h e l l o' The str function converts objects of other types into strings. Note: str does NOT concatenate a list of characters (or strings). See example on left. We can use the join method. It concatenates the elements in the list, separating them with the string that it is called on. Here: "" and " ".

Converting Strings Into Ints/Floats 21 >>> a = '2012' >>> b = int(a) >>> b 2012 >>> float(a) >>> a = "57 bus" >>> int(a) The int, float functions converts strings to integers and floats. Will give error message if the string does not represent an integer or float.

Converting Strings Into Lists 22 >>> a = "hello" >>> list(a) ['h', 'e', 'l', 'l', 'o'] The list function can convert a string to a list. Always works. Very handy if we want to manipulate a string's contents and create new strings based on them. (Like we did in an earlier example in this lecture)

The ASCII code In any string, each letter is represented by a value (the ASCII value): – ord(ch) function returns the numeric ASCII value of a character given as an argument >>> ord(‘a’) >>> ord(‘A’) >>> ord(‘1’) >>> ord(‘.’) – chr(i) function returns the character who’s ASCII code is i. >>> chr(97) 23

Strings with special characters >>> import string # this must be run before the following lines >>> string.punctuation '!"#$%&\'()*+,-./:; >>> string.digits ' ‘ >>> string.whitespace ' \t\n\r\x0b\x0c‘ >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz‘ >>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 24

Formatted output for strings “format string”.format(data1, data2,…) >>> “{} is {} years old”.format(“Bill”, 25) >>> print(“{} is {} years old”.format(“Bill”, 25)) Formatting commands will give directive about how corresponding data will be printed. – Alignment number:, ^ – Width number – Precision descriptor – Descriptor code s (strings) d (decimal) f (floating point decimal) e (floating point exponential) % (floating point as percent) Syntax: {:[align] [minimum_width] [.precision] [descriptor] } >>> “{:>10s} is {:<10d} years old”.format(“Bill”, 25) >>> “{:8.2%}”.format(2/3) >>> “{:8.2f}”.format(2/3) Where is this usefull? Can you see a use for it? 25

List methods You can find a list of the string methods in the Python Library Reference:  Go to: Sequence types – str, bytes,…  ml#sequence-types-str-bytes-bytearray-list-tuple-range ml#sequence-types-str-bytes-bytearray-list-tuple-range  scroll down to String Methods A few methods: – upper, lower, title, isupper, islower, istitle 26