0% found this document useful (0 votes)
15 views

6.2 - Manipulating Strings

Uploaded by

yiliawanghk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

6.2 - Manipulating Strings

Uploaded by

yiliawanghk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

PYTHON FOR

Strings – Part 1 EVERYBODY

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

Using in as a Logical Operator


• The in keyword can also be >>> fruit = 'banana'
>>> 'n' in fruit
used to check to see if one
True
string is “in” another string >>> 'm' in fruit
False
• The in expression is a >>> 'nan' in fruit
logical expression that True
returns True or False and >>> if 'a' in fruit :
... print('Found it!')
can be used in an if
...
statement Found it!
>>>
PYTHON FOR
Strings – Part 1 EVERYBODY

String Comparison
if word == 'banana':
print('All right, bananas.')

if word < 'banana':


print('Your word,' + word + ', comes before banana.')
elif word > 'banana':
print('Your word,' + word + ', comes after banana.')
else:
print('All right, bananas.')
PYTHON FOR
Strings – Part 1 EVERYBODY

• Python has a number of string


String Library
functions which are in the
string library (1 of 4)
>>> greet = 'Hello Bob'
• These functions are already >>> zap = greet.lower()
built into every string - we >>> print(zap)
invoke them by appending the hello bob
function to the string variable >>> print(greet)
Hello Bob
• These functions do not modify >>> print('Hi There'.lower())
the original string, instead they hi there
return a new string that has >>>
been altered
PYTHON FOR
Strings – Part 1 EVERYBODY

>>> stuff = 'Hello world'


>>> type(stuff)
<class 'str'>
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']

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

Making Everything UPPER CASE


• You can make a copy of a >>> greet = 'Hello Bob'
string in lower case or upper >>> nnn = greet.upper()
case >>> print(nnn)
HELLO BOB
• Often when we are searching >>> www = greet.lower()
for a string using find() we first >>> print(www)
convert the string to lower case hello bob
so we can search a string >>>
regardless of case
PYTHON FOR
Strings – Part 1 EVERYBODY

Search and Replace


• The replace() function >>> greet = 'Hello Bob'
>>> nstr = greet.replace('Bob','Jane')
is like a “search and >>> print(nstr)
replace” operation in a Hello Jane
word processor >>> nstr = greet.replace('o','X')
>>> print(nstr)
• It replaces all HellX BXb
>>>
occurrences of the
search string with the
replacement string
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 >>>

• strip() removes both


beginning and ending
whitespace
PYTHON FOR
Strings – Part 1 EVERYBODY

Prefixes
>>> line = 'Please have a nice day'
>>> line.startswith('Please')
True
>>> line.startswith('p')
False
PYTHON FOR
Strings – Part 1 EVERYBODY

Parsing and Extracting


21 31
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008

>>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'


>>> atpos = data.find('@')
>>> print(atpos)
21
>>> sppos = data.find(' ',atpos)
>>> print(sppos)
31
>>> host = data[atpos+1 : sppos]
>>> print(host)
uct.ac.za
PYTHON FOR
Strings – Part 1 EVERYBODY

Strings and Character Sets


Python 2.7.10 Python 3.5.1
>>> x = '이광춘' >>> x = '이광춘'
>>> type(x) >>> type(x)
<type 'str'> <class 'str'>
>>> x = u'이광춘' >>> x = u'이광춘'
>>> type(x) >>> type(x)
<type 'unicode'> <class 'str'>
>>> >>>

In Python 3, all strings are Unicode


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.

Initial Development: Charles Severance, University of Michigan


School of Information

… Insert new Contributors and Translators here

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy