Strings Exercises
String Basics
- Write Python code to do the following:
- Assign your first name to a variable named fullName
- Append (or add) a space and your last name to fullName
- Print out each of the characters in fullName with a while loop
- Display the number of characters in fullName
- Answer the following questions then confirm with your neighbor:
- What is the index of the first letter of your first name in fullName?
- What is the index of the first letter of your last name in fullName?
- How can we determine the length of any str variable in python?
- What will be the result of the following python code?
fullName[0] = 'Z'
- What does the following python script print out (if anything)?
word = "stressed"
startIndex = -1
lastIndex = 0 - len(word)
step = -1
for charIndex in range( startIndex, lastIndex + step, step):
print( word[ charIndex ], end='')
print()
String Methods
For each of the following methods, write down what they do including what they return:
- String testing methods:
- str.isalpha()
- str.isalnum()
- str.isdigit()
- str.islower()
- str.isspace()
- str.isupper()
- String modification methods:
- str.lower()
- str.upper()
- str.lstrip(), lstrip( chars )
- str.rstrip(), rstrip( chars )
- String searching and replacing methods:
- str.startswith( substring )
- str.endswith( substring )
- str.count( string )
- str.find( substring )
- str.replace( substring, newString )
- Non-string methods:
- int( str )
- float( str )
- bool( str )
String Slicing
- What will be the result of each of the following statements?
- print( fullName )
- print( fullName[ 5:8 ])
- print( fullName[ :8 ])
- print( fullName[ 5: ])
- print( fullName[ : ])
- print( fullName[ -3: ])
- print( fullName[-50: ])
- print( fullName[ :-2 ])
- print( fullName[ 5:50 ])
- print( fullName[ 5:10:2])
- print( fullName[ 5:10:3])
- What does the following python code display?
river = "Chattahoochee"
print( river )
print( river[1:4] )
print( river[2:4] )
print( river[4:5] + river[6:7] + river[11:12] )
print( river[6:8] + ', ' + river[6:8] + ', ' + river[10:] )
print( river[:4] )
print( river[-3:] )
print( river[:-3] )
print( river[9:1] )
Formatted String Literals
Strings can be formatted as in the following example:
mainDish = "pizza"
scoopsOfIceCream = 3
message = f'Dinner tonight is {mainDish} and {scoopsOfIceCream} types of ice-cream!'
print(message)
Output:
Dinner tonight is pizza and 3 types of ice-cream!
- The following Python code:
piApprox = 22/7
print( '22/7 is', piApprox )
displays 22/7 is 3.142857142857143
Use the piApprox variable and a formatted string (f-string) to display the following (exactly as shown): PI is approximately 3.14286
- Given the following python code,
iceCreamScoopCost = 1.50
display the following (exactly as shown) using an f-string and the variable iceCreamScoopCost:
The cost of one scoop is $1.50 and the cost of two scoops is $3.00.
- Use f-strings to display the following (exactly as shown):
Early computers limited the width of one line to 80 characters
These lines are right-justified at 80 characters
This line is centered in an 80-character column
String Comparison and Operators:
- What does the following Python code display and why?
print( chr( 67 ) )
print( chr( 68 ) )
print( chr( 69 ) )
print( ord( 'C' ) )
print( ord( 'S' ) )
Hint: What is the ASCII value for 'C'?
- Fill in the table with True or False:
|
|
OP |
|
|
< |
> |
== |
!= |
in |
not in |
A |
'python' OP 'pytHon' |
'python' < 'pytHon' False
|
|
|
|
|
|
C |
'py' OP 'python' |
|
|
|
|
|
|
D |
'python' OP 'rocks' |
|
|
|
|
|
|
E |
'python' OP 'python' |
|
|
|
|
|
|
String split() and join()
str.split()
str.split( substring ) cuts
str everywhere it finds
substring. It returns each part as a
str in a
list. By default,
split uses
' ' (a single space) as the delimiter.
For example, given
string = 'I love Python!', then
string.split() returns:
['I', 'love', 'Python!'] and
string.split('o') returns:
['I l', 've Pyth', 'n!']
- For each of the strings below, calculate how many cuts (i.e., how many elements are in the resulting list) when 1) split() is called on the string and 2) split( 'o' ) is called:
- I love python!
- Hello, world!
- supercalifragilisticexpialidocious
- See spot run. See spot run fast.
- What does the following code return:
dataHeaderLine = 'first name\tlast name\tage\tphone number\taddress'
dataHeaderLine.split( )
dataHeaderLine = 'first name\tlast name\tage\tphone number\taddress'
dataHeaderLine.split('\t')
eventDescription = "We're going to meet @ the building @ 7:00 PM"
eventDescription.split('@')
str.join()
str.join( listArg ) takes all of the elements in
listArg and puts the contents of
str between them. For example, given:
dataHeaderList = ['first name', 'last name', 'age', 'phone number', 'address']
separator = '\t'
then,
separator.join( dataHeaderList )
returns
first name last name age phone number address