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

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Container Types in Python
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
Introduction to Python
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Computing with Strings CSC 161: The Art of Programming Prof. Henry Kautz 9/16/2009.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Lists in Python.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
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
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
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.
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.
Strings CS303E: Elements of Computers and Programming.
Variables and Expressions CMSC 201 Chang (rev )
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
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.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
More Strings CS303E: Elements of Computers and Programming.
Copyright © Curt Hill Regular Expressions Providing a Search Pattern.
If Statements and Boolean Expressions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits:
Decision Structures, String Comparison, Nested Structures
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
Variables, Types, Expressions Intro2CS – week 1b 1.
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.
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.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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 CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
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.
Strings in Python String Methods. String methods You do not have to include the string library to use these! Since strings are objects, you use the dot.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
CSc 120 Introduction to Computer Programing II Adapted from slides by
Strings Part 1 Taken from notes by Dr. Neil Moore
Introduction to Strings
Introduction to Strings
Topics Introduction to File Input and Output
Introduction to C++ Programming
Python - Strings.
String Manipulation Chapter 7 Attaway MATLAB 4E.
CS 100: Roadmap to Computing
String and Lists Dr. José M. Reyes Álamo.
Introduction to Strings
CHAPTER 3: String And Numeric Data In Python
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Computer Science
Introduction to Strings
Python Strings.
Topics Introduction to File Input and Output
CS 100: Roadmap to Computing
Introduction to Strings
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Presentation transcript:

Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1

Strings Store Text In the same way that int and float are designed to store numerical values, the string type is designed to store text. Strings can be enclosed in: single quotes, double quotes, or triple double quotes. Examples: name = 'George' phone_number = " " message = """Please go shopping. We need milk, cereal, bread, cheese, and apples. Also, put gas in the car.""" 2

A Simple Program Using Strings text = input("please enter a day: ") weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] weekend = ['Saturday', 'Sunday'] if (text in weekdays): print('This is a weekday') elif (text in weekend): print('This is a weekend day') else: print('This is not a valid day') 3

Accessing the Elements of a String Accessing elements of a string is done as in lists, using the [] operator. >>> a = 'hello' >>> a[0] 'h' >>> a[2] 'l' >>> a[1:3] 'el' >>> a[-1] 'o' >>> a[-2] 'l' 4

Accessing the Elements of a String Accessing elements of a string is done as in lists, using the [] operator. >>> 'goodbye'[3] 'd' >>> 'goodbye'[4:1:-1] 'bdo' >>> 'goodbye'[::2] 'gobe' >>> 'goodbye'[:4] 'good' >>> 'goodbye'[4:] 'bye' 5

Concatenation Using The + Operator The string1+string2 expression produces the concatenation of string1 and string2. >>> a = "hello" >>> b = a + " " + "world" >>> print(b) hello world 6

Concatenation Using The += Operator The string1 += string2 statement assigns to string1 the concatenation of string1 and string2. >>> c = "Arlington" >>> c += ", TX" >>> print(c) Arlington, TX 7

The * Operator on Strings >>> a = "hello" >>> a*3 'hellohellohello' The string*integer expression repeats a string as many times as the integer specifies. 8

For Loops with Strings Print out all letters in a string. text = "hello world" for letter in text: print('found letter', letter) 9 OUTPUT: found letter h found letter e found letter l found letter o found letter found letter w found letter o found letter r found letter l found letter d

String Comparisons >>> my_strings = ["Welcome", "to", "the", "city", "of", "New", "York"] >>> my_strings ['Welcome', 'to', 'the', 'city', 'of', 'New', 'York'] >>> my_strings.sort() >>> my_strings ['New', 'Welcome', 'York', 'city', 'of', 'the', 'to'] Python uses a string order of its own. – Follows alphabetical order, with the exception that capital letters are always before lower case letters. 10

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 11

String Comparisons >>> "123" < "abc" True >>> "123" < "ABC" True Numbers come before letters. Guideline: do not memorize these rules, just remember that Python does NOT use exact alphabetical order. 12

String Comparisons >>> "123" == 123 What will this line produce? 13

String Comparisons >>> "123" == 123 False What will this line produce? – False, because a string cannot be equal to a number. 14

String Comparisons >>> "123" < 150 What will this line produce? 15

String Comparisons >>> "123" < 150 Traceback (most recent call last): File " ", line 1, in "123" < 123 TypeError: unorderable types: str() < int() What will this line produce? – An error message, because comparisons between strings and numbers are illegal in Python. 16

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 17

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. 18

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. We just assign to variable my_string a new string value, that is what we want. 19

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 20

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

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 print("the modified string is", my_string) 22

A Variation my_string = input("please enter a string: ") my_string = my_string[0:2] + "A" + my_string[3:] print("the modified string is", my_string) 23

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 24 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 25 >>> 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.

The len Function 26 >>> len('hello') 5 Similar as in lists, len returns the number of letters in a string.

Reversing a String >>> a = "hello" >>> b = a[::-1] >>> b 'olleh' >>> a[3:0:-1] 'lle' Slicing with step -1 can be used to reverse parts, or all of the string. 27

The index method 28 >>> a = [10, 11, 12, 10, 11] >>> a.index(10) 0 >>> a.index(11) 1 >>> b = "this is crazy" >>> b.index('i') 2 >>> b.index('cr') 8 The my_list.index(X) method returns the first position where X occurs. Gives an error if X is not in my_list. The my_string.index(X) behaves the same way, but: X can be a single letter or more letters.

The find method 29 >>> b = "this is crazy" >>> b.find('is') 2 >>> b.find('q') The my_string.find(X) method, like index, returns the first position where X occurs. X can be a single letter or more letters. Difference from index: my_string.find(X) returns -1 if X is not found.

The isspace method 30 >>> b = "\t\n \t" >>> b.isspace() True >>> "hello".isspace() False The my_string.isspace() method, returns True if the string only contains white space (space, tab, newline). X can be a single letter or more letters. " " is the space character. "\t" is the tab character. "\n" is the newline character.

The strip method 31 >>> a = " hello world " >>> b = a.strip() >>> b 'hello world' The my_string.strip() method, returns a string that is equal to my_string, except that white space (space, tab, newline) has been removed from the beginning and the end of my_string. White space in the middle of the string (between non- white-space characters) is not removed.

Converting Other Types to Strings 32 >>> a = 2012 >>> b = str(a) >>> b '2012' >>> a = ['h', 'e', 'l', 'l', 'o'] >>> b = str(a) >>> b "['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.

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

ASCII Codes Each letter corresponds to an integer, that is called the ASCII code for that letter. The ord function can be used to get the ASCII code of a letter. 34

ASCII Codes Each letter corresponds to an integer, that is called the ASCII code for that letter. The ord function can be used to get the ASCII code of a letter. for i in 'hello world': print(i, ord(i)) 35 OUTPUT: h 104 e 101 l 108 o w 119 o 111 r 114 l 108 d 100

From ASCII Code to Character The chr function can be used to get the letter corresponding to an ASCII code. 36

From ASCII Code to Character The chr function can be used to get the letter corresponding to an ASCII code. list1 = [104, 101, 108, 108, 111] text = "" for item in list1: text = text + chr(item) print("text =", text) 37 OUTPUT: text = hello

Converting Strings Into Lists 38 >>> 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.

Converting a List to a String To convert a list to a string, do not use the str function. >>> a = list('hello') >>> a ['h', 'e', 'l', 'l', 'o'] >>> b = str(a) >>> b "['h', 'e', 'l', 'l', 'o']" 39

Converting a List to a String To convert a list to a string, use a for loop. a = ['h', 'e', 'l', 'l', 'o'] b = "" for letter in a: b = b+letter >>> b 'hello' 40

Example: Strings to Lists and Back # sort all the letters in a string. text = input('Enter some text: ') text_list = list(text) text_list.sort() new_text = "" for letter in text_list: new_text = new_text + letter print("The sorted text is:", new_text) 41 OUTPUT: Enter some text: hello world The sorted text is: dehllloorw