Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Strings and Testingstring methods, formatting
testing approaches
CS 112 @ GMU
• string methods• string formatting• testing, unit testing
2
Topics
Some String Methods (See LIB 4.7.1)
usage: stringExpr . methodName ( args )
3
method purpose returned values.upper()s.lower()
converts letters to upper or lower case
modified copy of s
s.startswith(svar[,start[,stop]])s.endswith(svar[,start[,stop]])
is svar a prefix/suffix of s? bool
s.join(iterable) concatenates items from iterable, with copies of string s inbetweenthem.
string result of all those joined things
s.split(sep) get list of strings obtained by splitting s into parts at each occurrence of sep.
list of strings from between occurrences of sep
s.replace(old, new[,count]) replace all (or count) occurrencesof old str with new str.
string with replacements performed
Useful Tip: printing without a newline
print() specializations
• end=… : choose what print() adds at the end; default: "\n"• sep= … " choose what's printed between arguments; default: " "→ you have a lot of control over printing!
print("a",end='')print('b c', end='')print("d")
print(1,2,3,sep='.', end='!')print(4,5,6,sep='-->')
ab cd1.2.3!4-->5-->6
Formatting Strings
Brief introductions here, but also read the documentation.
Three approaches:• percent operator, % LIB 4.7.2 ZY 3.7
• format method LIB 6.1.3 ZY 7.5
• f-strings new as of Python 3.6
String Formatting: % operator
6
• describe pattern of string with placeholders, then supply all substitutions at once.
• Syntax: pattern_string % tuple
• Semantics:→ simplify lefthand string to value→ left to right, match placeholders in string with values from tuple→ substitutions obey special formatting directives
String Formatting: % operator
7
"there are %d days until %s." % (75, "holiday")
"%s ran %f miles today"% ("Zeke", 3.5)
"change is %d dollars and %d cents." % (4,39)
"you got %f%% of them, %s." % (0.95*100, "George")
"%s's number is %g/mol." % ("Avogadro",6.02214e23)
placeholder style of output accepted input
%d integer integers, floats
%f float integers, floats
%g float(scientific notation)
integers, floats – but it prefers scientific notation representation
%s string anything (calls str() )
%% the '%' character none – just represents the % symbol
<more> … don't memorize these: %i, %o, %u, %x, %X, %e, %E, %c, %r…
More Options
purpose examples resultsstate exact # columns after decimal point (%f)
"%.2f" % (2/3)"%.0f" % 15.5
'0.67''16'
state min. # columns for entire thing
"%4d" % 30"%3d" % 1234"%5f" % 2.5
' 30''1234'' 2.5'
use leading sign (+/-) "%+f" % 5 '+5.000000'
POLL – 5A
String formatting
The format( ) method
A powerful option to craft a string is the format method.• use { }'s as placeholders, put style rules inside
– examples: "{}" "{:4.2f}" "{:^5}"
• provide substitutions as arguments to .format() method
See more examples: LIB 6.1.3.2
More options…Again, indicate min # cols and exact # cols after the decimal.
• Show as percent:
• Align left/center/right:
"{:10.2}".format(0.123)
"{:%}".format(0.12)
"{:>6}".format("hi")"{:<6}".format("hi")"{:^6}".format("hi")"{:.^6}".format("hi")"{:o^6}".format("hi")
' hi''hi '' hi ''..hi..''oohioo'
' 0.12'
'12.000000%'
New! f-Strings
• special version of string literals with embedded expressions
• indicated with leading f in front of open-quote.
name = "George"age = 67print( f"Happy {age}th birthday, {name}!")
Some corner cases of f-strings
• you can call functions and methods:– f"{len(name)} letters long"– f"{name.upper()}!"
• watch out for clashing quote styles!(can't \escape them inside the {}'s)– f"{1+3} years"– f"{int('1')+3} years"– f"{int(\"1\")+3} years" FORBIDDEN
Testing Code
Notes on Debugging and Testing
• We basically never write 100% correct code on our first try• How can we debug our code? (identify the problem)• how can we thoroughly test it? (check for correct behavior)
Debugging code is essentially a careful analysis of all the assumptions about our code, to find the assumption that is false.Examples:→ I assume I used correct syntax.→ I assume I modified the correct variable.→ I assume the list (or some index) exists before I use it→ I assume this print statement happens each iteration→ I assume I'm editing the same file I'm running!
Locating the Syntax Error
Getting a syntax error on a "perfect" line of code? Look up to the previous line(s). You're likely missing a parenthesis, colon, or something else.
→ the indicated location is merely where Python got when it realized something was wrong.
line # code1 print("hello!")
2 n = int(input("please enter a number: ")
3 if n>0:
4 print("number is "+str(n))
5 else:
6 print("number was negative.")
demo$ python3 syntax_error.pyFile "syntax_error.py", line 3
if n>0:^
SyntaxError: invalid syntax
print-style debuggingruntime error: some value/variable can't be used that way. Did we build it wrong, or use it wrong?
print out relevant variables/expressions just before the offending operation occurs.Pros:→ access variables at the confusing portion of the code.→ Flexible, easy to include.Cons:→ need to be removed before code is ready to publish.→ Can introduce their own errors!→When overused, hard to tell what program is doing versus what debugging print statements are doing.
Drawing Out Memory
Run the code by hand or by using the visualizer.• preserve and identify aliases→ check with id() calls
• updates vs. re-assignments• make sure you perform the actions that are indicated, not
just what you think should happen!• seek where your expectations and actual performance
diverge. Did we forget to handle this situation, or are we handling it incorrectly?
Testing Approaches
Unit Testing – for the smallest parts of code you can manage, write tests that test this piece of code.• programmers often create large batches of unit
tests that can be rerun as desired – this is called "regression testing".→ all our testing files do this! J
• standardized ways of creating these exist but tend to use classes and objects – topics we haven't learned yet.
Two Testing Styles
Black box testing – "outsider's expectations". given a piece of code, think about what it is supposed to do, and create test cases that give specific inputs and look for the expected outputs/behavior (including tests that you expect to fail!)
White box testing – "code coverage." Looking at the actual structure of your code, think of test cases that should use/'touch' each part of the code, to make sure each part of the code works when used.
Practice Problem
def prime(n):is_prime = Truefor d in range(2,sqrt(n))
if d%n==0:is_prime = False
else:is_prime = True
return is_prime
This code is riddled with various kinds of errors!copy it from: http://cs.gmu.edu/~marks/112/examples/buggy.py• debug the code until it gets correct values.• choose blackbox test cases.• choose white box test cases.