Pythonlearn 06 Strings
Pythonlearn 06 Strings
1 2
Converting
Enter:Chuck
>>> print(name)
Looking Inside Strings
Chuck
• We prefer to read data in using
>>> apple = input('Enter:')
Enter:100
• We can get at any single character in a b a n a n a
strings and then parse and string using an index specified in
convert the data as we need
>>> x = apple – 10 0 1 2 3 4 5
Traceback (most recent call square brackets
>>> fruit = 'banana'
last): File "<stdin>", line 1,
• This gives us more control over
error situations and/or bad user
in <module> • The index value must be an integer >>>
>>>
letter = fruit[1]
print(letter)
TypeError: unsupported operand and starts at zero
input a
type(s) for -: 'str' and 'int'
• The index value can be an expression
>>> x = 3
>>> x = int(apple) – 10
• Input numbers must be >>> w = fruit[x - 1]
>>> print(x)
converted from strings that is computed >>> print(w)
90
n
3 4
10/01/21
5 6
7 8
10/01/21
9 10
11 12
10/01/21
13 14
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
• We can also look at any
continuous section of a string
More String Operations using a colon operator >>> s = 'Monty Python'
>>> print(s[0:4])
• The second number is one Mont
beyond the end of the slice - >>> print(s[6:7])
“up to but not including” P
>>> print(s[6:20])
• If the second number is
Python
beyond the end of the string,
it stops at the end
15 16
10/01/21
17 18
19 20
10/01/21
21 22
String Library
str.capitalize() str.replace(old, new[, count])
str.center(width[, fillchar]) str.lower()
str.endswith(suffix[, start[, end]]) str.rstrip([chars])
str.find(sub[, start[, end]]) str.strip([chars])
str.lstrip([chars]) str.upper()
23 24
10/01/21
25 26
27 28
10/01/21
Parsing and
Prefixes Extracting
21 31
>>> line = 'Please have a nice day' From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
>>> line.startswith('Please')
True >>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
>>> atpos = data.find('@')
>>> line.startswith('p') >>> print(atpos)
False 21
>>> sppos = data.find(' ',atpos)
>>> print(sppos)
31
>>> host = data[atpos+1 : sppos]
>>> print(host)
uct.ac.za
29 30
31 32
10/01/21
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance ...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.
33