Strings

6
Strings The Basics

description

Strings. The Basics. Strings. a collection data type can refer to a string variable as one variable or as many different components (characters) string values are delimited by either single quotes or double quotes operators + and * (overloaded operators) - PowerPoint PPT Presentation

Transcript of Strings

Page 1: Strings

StringsThe Basics

Page 2: Strings

Strings

• a collection data type• can refer to a string variable as one variable or as many different

components (characters)• string values are delimited by either single quotes or double quotes• operators + and * (overloaded operators)• + “concatenation” sticks two strings together to get a new string• * “replication” repeats a string a given number of times to give a new string• precedence is * above +• order of concatenation matters! “a” + “b” is not the same as “b” + “a”

Page 3: Strings

Indexing

• Also called subscripts• A way to tell individual characters of a string apart• notation like that used for lists• [ ] with an integer (constant or variable) inside• Strings are numbered from 0 on left end and increasing• Strings are also numbered from -1 on right end and decreasing• You can use an expression as an index also, like str[k + 1], as long as

the expression has an integer value

Page 4: Strings

The len function

• Note this is a function, not a method (do not call it with the dot notation)• len operates on one argument, either a string or a list• returns an integer result, tells how many characters are in the string or

how many elements are in the list• lowest return value is zero for the empty string• Python claims “no upper limit on string length”, literally it depends on

your environment – how much RAM you have, which OS you are running, on a typical PC today with Windows it is around 2 billion characters• s[len(s)] would give an error! Remember that len tells you how many

characters, not what the last subscript in the string would be

Page 5: Strings

chr and ord functions

• Sometimes you need to work with the ASCII codes of individual characters• chr(integer) will return the character corresponding to the ASCII code

argument, example chr(65) will return “A”• ord(char) will return the ASCII code (as an integer) of the single

character that you send, example ord(“A”) will return 65• In general, use the characters instead of their ASCII values in coding, it

will be much more obvious what you are doingDo NOT say “if ch >= 65 and ch <= 90” when you are checking for upper caseit is MUCH better to say if ch >= “A” and ch <=“Z” or even if ch in ascii_uppercase or if ch.isupper()

Page 6: Strings

The slice operator

• The “substring” operator in Python• See separate set of slides