6.2 - Manipulating Strings
6.2 - Manipulating Strings
String Concatenation
>>> a = 'Hello'
>>> b = a + 'There'
When the + operator is >>> print(b)
applied to strings, it means HelloThere
“concatenation” >>> c = a + ' ' + 'There'
>>> print(c)
Hello There
>>>
PYTHON FOR
Strings – Part 1 EVERYBODY
String Comparison
if word == 'banana':
print('All right, bananas.')
https://docs.python.org/3/library/stdtypes.html#string-methods
PYTHON FOR
Strings – Part 1 EVERYBODY
PYTHON FOR
Strings – Part 1 EVERYBODY
String Library (4 of 4)
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()
PYTHON FOR
Strings – Part 1 EVERYBODY
Searching a String
b a n a n a
• We use the find() function to search
for a substring within another string 0 1 2 3 4 5
>>> fruit = 'banana'
• find() finds the first occurrence of the >>> pos = fruit.find('na')
substring >>> print(pos)
2
• If the substring is not found, find() >>> aa = fruit.find('z')
returns -1 >>> print(aa)
-1
• Remember that string position starts
at zero
PYTHON FOR
Strings – Part 1 EVERYBODY
Stripping Whitespace
• Sometimes we want to take >>> greet = ' Hello Bob
>>> greet.lstrip()
'
a string and remove
'Hello Bob '
whitespace at the beginning >>> greet.rstrip()
and/or end ' Hello Bob'
>>> greet.strip()
• lstrip() and rstrip() remove 'Hello Bob'
whitespace at the left or right >>>
Prefixes
>>> line = 'Please have a nice day'
>>> line.startswith('Please')
True
>>> line.startswith('p')
False
PYTHON FOR
Strings – Part 1 EVERYBODY
Summary
• String type • String operations
• Read/Convert • String library
• Indexing strings [] • String Comparisons
• Slicing strings [2:4] • Searching in strings
• Looping through strings • Replacing text
with for and while • Stripping white space
• Concatenating strings with +
PYTHON FOR
Strings – Part 1 EVERYBODY
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.