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

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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
Characters and Strings. Characters In Java, a char is a primitive type that can hold one single character A character can be: –A letter or digit –A punctuation.
Computing with Strings CSC 161: The Art of Programming Prof. Henry Kautz 9/16/2009.
Introduction to Computing Using Python Chapter 6  Encoding of String Characters  Randomness and Random Sampling.
Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Q and A for Sections 2.3 – 2.5 CS 106 Professor Victor T. Norman, DDS.
Introduction to Python
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
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.
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 © 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.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 3 Mathematical Functions, Strings, and Objects.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
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.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
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.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
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
Chapter 8 - Characters and Strings
Advanced Programming Behnam Hatami Fall 2017.
Introduction to Strings
Introduction to Strings
Introduction to Python
CHAPTER THREE Sequences.
Python - Strings.
Data types Numeric types Sequence types float int bool list str
Chapter 3 Mathematical Functions, Strings, and Objects
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
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 Strings.
Topics Basic String Operations String Slicing
By Himanshi dixit 11th ’B’
Introduction to Strings
Intro to Computer Science CS1510 Dr. Sarah Diesburg
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 (UTF-8 for Python) 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' vs 'Bob\'s' The triple quotes preserve formatting (new lines). You can use them for longer comments. – Using the str constructor: str(123) String operators: +, * – Strings can be concatenated together with + >>> 'This' + ' is a ' + ' new string.' – String repetitions: >>> 'apple' * 3 >>> 'apple' * 0 4

Converting Other Types to Strings 5 >>> a = 2012 >>> b = str(a) >>> b '2012' The str function converts objects of other types into strings.

Converting Strings Into Ints/Floats 6 >>> 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.

The in Operator >>> vowels = "aeiou" >>> "a" in vowels True >>> "k" in vowels False 7 Syntax: element in container Returns true if the element appears in the container, false otherwise.

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 len function gives the length of a string >>> len(my_str) 8

index and find 9 >>> 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. Does not work for lists.

upper and lower 10 >>> 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 UTF-8 code Characters are represented in the computer as numbers: – Python uses the UTF-8 encoding system – ASCII (the American Standard Code for Information Interchange) earlier encoding system (128 characters), you may see references to it. UTF-8 is backward compatible with it. – Unicode set – contains over a million characters from 93 scripts(alphabets) – UTF-8 (Universal Character Set Transformation Format – 8bit) – 1993 In any string, each letter is represented by a value (the ASCII value): – ord(ch) function returns the numeric UTF-8 value of a character given as an argument >>> ord('a') >>> ord('A') see others: '1', '.', '\n' – chr(i) function returns the character who’s UTF-8 code is i. >>> chr(97) ord vs int – Do not confuse the UTF-8 value of a character with the value of the character viewed as a number: ord(ch) vs int(ch) >>> ord ('1') >>> int ('1') 11

Subset of UTF-8 See Appendix D for the full set of ASCII (book slide)

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 of different lengths Python uses the UTF-8 value to compare characters. Capital letters are always before lower case letters. Numbers are always before letters. 13

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 14

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 15

Strings are immutable Strings can not 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 16

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

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

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

Write a program that: – Gets a string from the user. – Modifies that string so that position 3 is an A. – Prints the modified string. 20 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) 21

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) 22

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) 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

Escape sequences Escape sequences (non-printing characters): – \n : new line (when printing, move to a new line) – \t : tab (when printing, place a tab) – \ : the string continues on the next line (it will be printed on the same line) – \\ : allows you to print the \ : 'This is a backslash: \\' – \' : allows you to print the ' : 'Bob\'s' 25

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

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 – Sample methods: split, upper, lower, title, isupper, islower, istitle 27