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

Python 04 String

Python_04_String

Uploaded by

2200010487
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python 04 String

Python_04_String

Uploaded by

2200010487
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

STRING

Strings
index 0 1 2 3 4 5 6 7
or -8 -7 -6 -5 -4 -3 -2 -1
character P . D i d d y

>>> name = "P. Diddy"


• Accessing character(s): >>> name[0]
'P'
variable [ index ] >>> name[7]
variable [ index1:index2 ] 'y'
>>> name[-1]
'y'
>>> name[3:6]
– index2 exclusive 'Did'
>>> name[3:]
– index1 or index2 can be 'Diddy'
omitted (goes to end of string) >>> name[:-2]
'P. Did'

2
String Methods
Java Python
length len(str)
startsWith, endsWith startswith, endswith
toLowerCase, toUpperCase upper, lower,
isupper, islower,
capitalize, swapcase
indexOf find
trim strip

>>> name = "Martin Douglas Stepp"


>>> name.upper()
'MARTIN DOUGLAS STEPP'
>>> name.lower().startswith("martin")
True
>>> len(name)
20

3
Looping Through Strings

Using a while statement, fruit = 'banana' 0b


an iteration variable, and index = 0 1a
the len function, we can while index < len(fruit): 2n
letter = fruit[index] 3a
construct a loop to look at
print(index, letter)
each of the letters in a 4n
index = index + 1
string individually 5a
Looping Through Strings

• A definite loop using a b


for statement is much a
fruit = 'banana'
more elegant n
for letter in fruit:
a
• The iteration variable is print(letter)
n
completely taken care of a
by the for loop
Looping Through Strings

• A definite loop using a fruit = 'banana'


for letter in fruit :
b
for statement is much a
print(letter)
more elegant n
a
• The iteration variable is index = 0
n
completely taken care of while index < len(fruit) :
letter = fruit[index] a
by the for loop
print(letter)
index = index + 1
Looping and Counting

word = 'banana'
This is a simple loop that count = 0
loops through each letter in a for letter in word :
string and counts the number if letter == 'a' :
of times the loop encounters count = count + 1
the 'a' character print(count)
Looking Deeper into in

• The iteration variable


“iterates” through the Iteration Six-character
sequence (ordered set) variable string
• The block (body) of code is
executed once for each value for letter in 'banana' :
in the sequence print(letter)
• The iteration variable moves
through all of the values in the
sequence
Yes No b a n a n a
Done? Advance letter

print(letter)

for letter in 'banana' :


print(letter)

The iteration variable “iterates” through the string and the block (body)
of code is executed once for each value in the sequence
More String Operations
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
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
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

>>> s = 'Monty Python'


If we leave off the first number >>> print(s[:2])
or the last number of the slice, Mo
it is assumed to be the >>> print(s[8:])
beginning or end of the string thon
respectively >>> print(s[:])
Monty Python
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
>>>
Using in as a Logical Operator

>>> fruit = 'banana'


• The in keyword can also be >>> '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
True
logical expression that >>> if 'a' in fruit :
returns True or False and ... print('Found it!')
can be used in an if ...
statement Found it!
>>>
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.')
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()
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

• find() finds the first occurrence of the >>> fruit = 'banana'


substring >>> pos = fruit.find('na')
>>> print(pos)
• If the substring is not found, find() 2
returns -1 >>> aa = fruit.find('z')
>>> print(aa)
• Remember that string position starts -1
at zero
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
Search and Replace

• The replace() function


is like a “search and >>> greet = 'Hello Bob'
replace” operation in a >>> nstr = greet.replace('Bob','Jane')
>>> print(nstr)
word processor Hello Jane
>>> nstr = greet.replace('o','X')
• It replaces all >>> print(nstr)
occurrences of the HellX BXb
search string with the >>>
replacement string
Stripping Whitespace
• Sometimes we want to take
a string and remove
whitespace at the beginning >>> greet = ' Hello Bob '
>>> greet.lstrip()
and/or end
'Hello Bob '
>>> greet.rstrip()
• lstrip() and rstrip() remove ' Hello Bob'
whitespace at the left or right >>> greet.strip()
'Hello Bob'
• strip() removes both >>>
beginning and ending
whitespace
Prefixes
>>> line = 'Please have a nice day'
>>> line.startswith('Please')
True
>>> line.startswith('p')
False
Parsing and
21 31 Extracting
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
Exercise
1. Write a function to find the length of a string (don't use the
len() function)
2. Write a program to count the number of words in a string
(assume the words in the string are separated by a space)
3. Write a function to count the number of vowels (a e i o u)
and consonants in the string

23

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