252x Filetype PDF File size 2.51 MB Source: cs.gmu.edu
The String Data Type
Python Programming: • The most common use of personal
An Introduction to computers is word processing.
Computer Science • Text is represented in programs by the
string data type.
Chapter 4 • A string is a sequence of characters
Computing with Strings enclosed within quotation marks (") or
apostrophes (') or (“””).
Coming up: The String Data Type 1
CCoommiinngg uupp:: EExxaammpplleess 22
Examples Newline string examples
>>> str1="Hello" To create a string with a newline (“return”) in it,
>>> str2='spam' you can add a newline character \n .You can
>>> print str1, str2 think of newline as the character produced
Hello spam when you press the key
>>>print “The newspaper is \n at the door”
>>> type(str1) The newspaper is
at the door
>>> type(str2) >>> print “Mary: John? \nJohn: Yes \nMary: Your car is on fire”
Mary: John?
John: Yes
Mary: Your car is on fire
CCoommiinngg uupp:: NNeewwlliinnee ssttrriinngg eexxaammpplleess 33 CCoommiinngg uupp:: LLiinnee ccoonnttiinnuuaattiioonn eexxaammpplleess 44
1
Line continuation examples “”” triple-quotes examples
To create a very long string you may want to define it on Triple-quotes “”” tells Python to include newline
multiple lines, for this you can use the line characters and you do not need the line continuation
continuation character “\” characters. This is useful if you have a large block of
formatted text, just type it as you want it to look.
>>>hello = "This is a rather long string containing\n\ >>> str1=“”"
several lines of text just as you would do in C.\n\ Usage: thingy [OPTIONS]
Note that whitespace at the beginning of the line is\ -h Display this usage message
significant." -H hostname Hostname to connect to
>>>print hello """
This is a rather long string containing >>> print str1
several lines of text just as you would do in C. Usage: thingy [OPTIONS]
Note that whitespace at the beginning of the line is significant. -h Display this usage message
-H hostname Hostname to connect to
CCoommiinngg uupp:: ““”””” ttrriippllee--qquuootteess eexxaammpplleess 55 CCoommiinngg uupp:: WWhhyy iinnppuutt ddooeessnn’’tt wwoorrkk 66
Why input doesn’t work Why Input Doesn’t Work (cont)
>>> firstName = input("Please enter your name: ") • The input statement is a delayed expression.
Please enter your name: John • When you enter a name, it’s doing the same
Traceback (most recent call last): thing as:
File "", line 1, in -toplevel- firstName = John
firstName = input("Please enter your name: ") • The way Python evaluates expressions is to
File "", line 0, in -toplevel- look up the value of the variable John and
NameError: name 'John' is not defined store it in firstName.
• What happened? • Since John didn’t have a value, we get a
NameError.
CCoommiinngg uupp:: WWhhyy IInnppuutt DDooeessnn’’tt WWoorrkk ((ccoonntt)) 77 CCoommiinngg uupp:: UUssiinngg qquuootteess ttoo aavvooiidd tthhee pprroobblleemm 88
2
Using quotes to avoid the problem Using raw_input to avoid the problem
• One way to fix this is to enter your string • There is a better way to handle text – the
input with quotes around it: raw_input function.
>>> firstName = input("Please enter your name: ") • raw_input is like input, but it doesn’t evaluate
Please enter your name: "John" the expression that the user enters.
>>> print "Hello", firstName
Hello John >>> firstName = raw_input("Please enter your name: ")
• Even though this works, this is Please enter your name: John
cumbersome! >>> print "Hello", firstName
Hello John
CCoommiinngg uupp:: UUssiinngg rraaww__iinnppuutt ttoo aavvooiidd tthhee pprroobblleemm 99 CCoommiinngg uupp:: AAcccceessssiinngg iinnddiivviidduuaall cchhaarraacctteerrss 1010
Accessing individual characters Indexing example
• We can access the individual
characters in a string through indexing. H e l l o B o b
• The positions in a string are numbered 0 1 2 3 4 5 6 7 8
from the left, starting with 0. >>> greet = "Hello Bob"
• The general form is [], >>> greet[0]
where the value of expr determines 'H'
>>> print greet[0], greet[2], greet[4]
which character is selected from the H l o
string. >>> x = 8
>>> print greet[x - 2]
B
CCoommiinngg uupp:: IInnddeexxiinngg eexxaammppllee 1111 CCoommiinngg uupp:: IInnddeexxiinngg eexxaammppllee -- ffrroomm tthhee rriigghhtt 1212
3
Indexing example - from the right What about a substring?
Slicing a string
• Slicing:
H e l l o B o b [:]
0 1 2 3 4 5 6 7 8 • start and end should both be ints
• In a string of n characters, the last character • The slice contains the substring
is at position n-1 since we start counting with
0. beginning at position start and runs up
• We can index from the right side using to but doesn’t include the position
negative indexes. end.
>>> greet[-1]
'b'
>>> greet[-3]
'B'
CCoommiinngg uupp:: WWhhaatt aabboouutt aa ssuubbssttrriinngg?? 1313 CCoommiinngg uupp:: SSlliicciinngg EExxaammppllee 1414
SSlliicciinngg aa ssttrriinngg
Slicing Example String Operators
H e l l o B o b
0 1 2 3 4 5 6 7 8 9 Operator Meaning
>>> greet[0:3] + Concatenation
'Hel'
>>> greet[5:9] * Repetition
' Bob'
>>> greet[:5] [] Indexing
'Hello' Hint: When slicing it helps
>>> greet[5:] to think of the slide indexes [:] Slicing
' Bob' between the characters,
>>> greet[:] len() Length
'Hello Bob' then 0:3 is very clear
for in Iteration through
characters
CCoommiinngg uupp:: SSttrriinngg OOppeerraattoorrss 1515 CCoommiinngg uupp:: CCoonnccaatteennaattiioonn ((ssttrr ++ ssttrr)) 1616
4
no reviews yet
Please Login to review.