Py4Inf 06 Strings Print PDF
Py4Inf 06 Strings Print PDF
String Data Type >>> str1 = "Hello" Reading and >>> name = raw_input('Enter:')
>>> str2 = 'there'
• A string is a sequence of >>> bob = str1 + str2 Converting Enter:Chuck
>>> print name
>>> print bob Chuck
characters
Hellothere • We prefer to read data in
>>> apple = raw_input('Enter:')
using strings and then parse
• A string literal uses quotes ‘Hello’ >>> str3 = '123'
>>> str3 = str3 + 1 and convert the data as we Enter:100
or “Hello” >>> x = apple - 10
Traceback (most recent call last): need
Traceback (most recent call last):
• For strings, + means “concatenate” File "<stdin>", line 1, in <module>
• This gives us more control File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' over error situations and/ TypeError: unsupported operand
• When a string contains numbers, it and 'int' objects or bad user input type(s) for -: 'str' and 'int'
is still a string >>> x = int(str3) + 1 >>> x = int(apple) - 10
• We can convert numbers in a
>>> print x
124
• Raw input numbers must >>> print x
90
string into a number using int() be converted from strings
>>>
Looking Inside Strings A Character Too Far
M o n t y P y t h o n
Yes 0 1 2 3 4 5 6 7 8 9 10 11
b a n a n a
Done? Advance letter
• We can also look at any >>> s = 'Monty Python'
continuous section of a string >>> print s[0:5]
print letter
using a colon operator Monty
letter
>>> print s[6:7]
for letter in 'banana' :
• The second number is one
P
beyond the end of the slice -
print letter >>> print s[6:20]
“up to but not including”
Python
• If the second number is
The iteration variable “iterates” though the string and the block beyond the end of the string,
(body) of code is executed once for each value in the sequence it stops at the end Slicing Strings
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11 String Concatenation
>>> s = 'Monty Python' >>> a = 'Hello'
>>> print s[:2] >>> b = a + 'There'
Mon
• If we leave off the first
>>> print s[8:]
>>> print b
number or the last number of
thon • When the + operator is HelloThere
>>> c = a + ' ' + 'There'
the slice, it is assumed to be applied to strings, it
>>> print s[:] >>> print c
the beginning or end of the means "concatenation"
Monty Python Hello There
string respectively
>>>
Slicing Strings
What is a string.py
Two ways to call the library
Library? def split(inp):
blah
>>> greet = 'Hello Bob' blah
• We can call string functions by >>> zap = greet.lower() • Some super developers
appending the function name to the >>> print zap in the Python world
string variable hello bob write the libraries for us def upper(inp):
>>> print 'Hi There'.lower() to use for i in blah:
• We can import the string library and hi there blah
pass the string as a parameter >>> import string • Somewhere there is a
>>> print string.lower('Hi There') file string.py with a def find(inp):
hi there bunch of def statements
blah
blah
>>> stuff = 'Hello world'
>>> type(stuff)
<type 'str'>
>>> dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
http://docs.python.org/lib/string-methods.html http://docs.python.org/lib/string-methods.html
>>> greet = 'Hello Bob' • The replace() function >>> greet = "Hello Bob"
• You can make a copy of a string in >>> nnn = greet.upper() is like a “search and >>> nstr = greet.replace("Bob","Jane")
>>> print nstr
lower case or upper case >>> print nnn replace” operation in
a word processor Hello Jane
HELLO BOB
• Often when we are searching for a
>>> www = greet.lower()
>>> greet = "Hello Bob"
string using find() - we first convert
>>> print www • It replaces all >>> nstr = greet.replace("o","X")
the string to lower case so we can occurrences of the >>> print nstr
search a string regardless of case hello bob search string with the HellX BXb
>>> replacement string >>>
line = 'Please' >>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
line.lower().startswith('p') >>> atpos = data.find('@')
>>> print atpos
21
>>> sppos = data.find(' ',atpos)
'please'.startswith('p') >>> print sppos
31
>>> host = data[atpos+1 : sppos]
When we use line.lower() - it returns a string than then we >>> print host
call startswith('p') on that returned string. uct.ac.za
• The percent-sign (%) is a "formatting operator" that takes a string with • We are often presented with input that we need to break into pieces
format sequences and a list of variables to "poke" into the string
• We use the string.split() function to break a string into a list of strings
>>> camels = 42
>>> 'I have spotted %d camels.' % camels >>> abc = 'With three words'
'I have spotted 42 camels.' >>> stuff = abc.split()
>>> 'Hi %s have a nice %s!' % ('Chuck', 'week') >>> print stuff
'Hi Chuck have a nice week!' ['With', 'three', 'words']
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') >>>
'In 3 years I have spotted 0.1 camels.'
Summary
• String type • String comparison