Chapter 5 Strings CSC1310 Fall 2009. Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.

Slides:



Advertisements
Similar presentations
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Advertisements

Java Programming Strings Chapter 7.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© 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.
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
String Escape Sequences
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
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.
2440: 211 Interactive Web Programming Expressions & Operators.
System development with Java Lecture 2. Rina Errors A program can have three types of errors: Syntax and semantic errors – called.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 12 More about strings 05/02/09 Python Mini-Course: Day 3 – Lesson 12.
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.
Chapter 2: Using Data.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Chapter 2 Variables.
C++ Basics Tutorial 5 Constants. Topics Covered Literal Constants Defined Constants Declared Constants.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Strings See Chapter 2 u Review constants u Strings, concatenation and repetition 1.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Standard Types and Regular Expressions CS 480/680 – Comparative Languages.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
JavaScript and Ajax (JavaScript Data Types) Week 2 Web site:
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
17-Mar-16 Characters and Strings. 2 Characters In Java, a char is a primitive type that can hold one single character A character can be: A letter or.
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.
LECTURE 5 Strings. STRINGS We’ve already introduced the string data type a few lectures ago. Strings are subtypes of the sequence data type. Strings are.
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.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
String and Lists Dr. José M. Reyes Álamo.
Do-more Technical Training
Chapter 2 Variables.
Topics Designing a Program Input, Processing, and Output
String Processing Upsorn Praphamontripong CS 1110
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Chapter 8 - Characters and Strings
Basic Python Collective variables (sequences) Lists (arrays)
CHAPTER THREE Sequences.
Data types Numeric types Sequence types float int bool list str
String and Lists Dr. José M. Reyes Álamo.
Fundamentals of Python: First Programs
CHAPTER 3: String And Numeric Data In Python
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
Python Strings.
Chapter 2 Variables.
Strings As well as tuples and ranges, there are two additional important immutable sequences: Bytes (immutable sequences of 8 ones and zeros (usually represented.
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Chapter 5 Strings CSC1310 Fall 2009

Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based information. immutable sequencesleft- to-right order Strings in Python are immutable (e.g., cannot be changed in place) sequences (e.g., they have a left- to-right order).

Single and Double Quotes interchangeable. Single and double quotes are interchangeable. >>> ‘Python’, “Python” Empty literal‘’“” Empty literal: ‘’ or “”. It allows you to embed a quote character of the other type inside a string: “’”‘”’ >>> “knight’s”,‘knight”s’ Python automatically concatenates adjacent strings ””‘ ’“ the ” >>>”Title” ‘ of’ “ the book”

Escape Sequences Escape sequencebyte code Escape sequence is a special byte code embedded into string, that can not be easily typed on a keyboard. \ with one (or more) character(s) single character \ with one (or more) character(s) is replaced by a single character in the resulting string. \n \n - Newline \t \t - Horizontal Tab >>> s=‘a\nb\tc’ # 5 characters! >>> s ‘a\nb\tc’ >>> print s a bc

Escape Sequences \\ \\ - Backslash \’ \’ - Single quote \” \” - Double quote \a \a - Bell \b \b - Backspace \r \r - Carriage return \xhh \xhh - Hex digits value hh \0 \0 - Null (binary zero bytes) >>> print ‘a\0m\0c’ # 5 characters! a m c

Raw Strings >>>print ‘C:\temp\new.txt’ \\\\ >>>print ‘C:\\temp\\new.txt’ Raw string suppress escape Format: r“text” r‘text’(R“text” R‘text’) Format: r“text” or r‘text’(R“text” or R‘text’) r’ >>>print r‘C:\temp\new.txt’ Raw strings may be used for directory paths, text pattern matching.

Triple Quoted Strings or Block Strings Block string Block string is a convenient literal format for coding multiline text data (error msgs, HTML or XML code). Format: “”” ””” ‘’’’’’ Format: “”” text””” or ‘’’text’’’

Unicode Strings Unicode (“wide” character) strings Unicode (“wide” character) strings are used to support non-latin characters that require more than one byte in memory. Format: u“text” u‘text’(U“text” U‘text’) Format: u“text” or u‘text’(U“text” or U‘text’) Expression with Unicode and normal strings has Unicode string as a result. >>>’fall’+u’08’ u’fall08’ strunicode >>>str(u’fall08’),unicode(‘fall08’) ‘fall08’,u’fall08’

Basic operations: len(), +, *,in len(str)str. len(str) function returns the length of a string str. >>>len(‘abc’) str1+str2 (concatenation) str1str2 str1+str2 (concatenation) creates a new string by joining operands str1 and str2. >>>‘abc’ + ‘def’,len(‘abc’ + ‘def’) str*i (repeat) stri str*i (repeat) adds a string str to itself i times. >>> print ‘-’ * 80 str 1 in str2 (membership)str1 str2 str 1 in str2 (membership) returns true if str1 is a substring of str2; otherwise, returns false. >>>day=‘Monday 8th Sept 2008’ >>>’sep’ in day >>>’th Sep’ in day

Indexing index Each character in the string can be accessed by its position (offset) – index. >>>S = ‘STRINGINPYTHON’ –xx th Negative offset can be viewed as counting backward from the end(offset –x is x th character from the end). >>>S[0],S[10],S[13],S[-5],S[-14] (‘S’,’T’,’N’,’Y’,’S’) >>>S[14],S[-15]

Slicing substring Slicing allows us to extract an entire section (substring) in a single step. Str1[offset1:offset2]substringstr1 from offset1 (including)at offset2 (excluding). Str1[offset1:offset2] returns a substring of str1 starting from offset1 (including) and ending at offset2 (excluding). >>>S[1:3] #extract item at offsets1 and 2 >>>S[1:] #all items past the first >>>S[:3] # extract items at offsets 0,1,2 >>>S[:-1] #fetch all but the last item >>>S[-1:] # extract last item copy >>>S[:] # a copy of the string

In Python 2.3 Third index – stride(step) >>>S=‘ ’ >>>S[1:10:2] ‘13579’ To reverse string use step =-1 >>>”hello”[::-1]

String Conversion You cannot add a number and a string together. int(str1)str1 int(str1) converts string str1 into integer. float(str1)str1 float(str1) converts string str1 into floating-point number. string.atoi(str1) string.atof(str1). Older techniques: functions string.atoi(str1) and string.atof(str1). >>>int(“42”)+1,float(“42”)+1 str(i)i`i` str(i) converts numeric i to string(`i`) >>>”fall0”+str(8)

Changing Strings You cannot change a string in-place by assigning value to an index(S[0] = ‘X’) To modify: create new string with concatenation and slicing. >>>s=‘spam’ += >>>s=s+” again” # s+=” again!” >>>s >>>s=s[:3]+” is here”+s[-1:] >>>s Alternatively, format a string.

Formatting Strings “format string” % “object to insert” “format string” % “object to insert” >>>s=“Sales tax” >>>s=”%s is %d percent!” % (s,8) %s %s string %d %d decimal integer %i%u %i integer (%u - unsigned integer) %o %o octal integer %x%X %x hex integer (%X – uppercase hex integer) %e%E %e floating-point exponent (%E - uppercase) %f%F %f floating-point decimal (%F – uppercase)

String Methods (p.91 table 5-4) Str1.replace(str2,str3)str2 Str1str3 Str1.replace(str2,str3) replaces each substring str2 in Str1 to str3. >>>‘string in python’.replace( ‘in’, ‘XXXX’) Str1.find(str2) str2Str1, Str1.find(str2) returns the offset where substring str2 appears in Str1, or -1. >>>where =‘string in python’.find( ‘in’) >>>’string in python’[:where] >>>‘in1in2in3in4in5’.replace( ‘in’, ‘XX’,3)

String Methods Str.upper(), str.lower(), str.swapcase() Str1.count(substr,start,end) Str1.endswith(suffix,start,end) Str1.startswith(prefix,start,end) Str1.index(substr,start,end) Str1.isalnum(),str1.isalpha(), str1.isdigit(), str1.islower(),str1.isspace(),str1.issupper()

String Module Maketrans()/translate() Maketrans()/translate() >>>import string >>>convert=string.maketrans(“ _-”,”_-+”) >>>input=“It is a two_part – one_part” >>>input.translate(convert) ‘It_is_a_two-part_+_one-part’

String Module Constants Constants  digits ‘ ’  octdigits ‘ ’  hexdigits ‘ abcdefABCDEF’  lowercase ‘abcdefghijklmnopqrstuvwxyz’  uppercase ‘ABCDEFGHIJKLMNOPRQSTUVWXYZ ’  letters lowercase+uppercase  whitespace ‘\t\n\r\v’ >>>import string >>>x=raw_input() >>>x in string.digits