Upcoming SlideShare
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Standard text messaging rates apply

# Python & Perl: Lecture 06

976

Published on

Published in: Technology, Education
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total Views
976
On Slideshare
0
From Embeds
0
Number of Embeds
18
Actions
Shares
0
0
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Transcript

• 1. Python & Perl Lecture 06 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
• 2. Outline ● Strings ● Object Comparison ● Loopswww.youtube.com/vkedco www.vkedco.blogspot.com
• 4. Strings ● Strings are immutable sequences, i.e. they cannot be modified after they are created >>> x = [1, 2, 3] >>> x[1] = 5555 # this is OK >>> y = (1, 2, 3) >>> y[1] = 9999 # error >>> z = spam >>> z[1] = P # errorwww.youtube.com/vkedco www.vkedco.blogspot.com
• 5. Strings ● Let us print a 2-D matrix: matrix = [[1, 2, 3], [11, 22, 33], [111, 222, 333]] for row in matrix: for col in row: print col, print ## this prints n ● If you run the above for loop, you notice that the numbers do not line up nicelywww.youtube.com/vkedco www.vkedco.blogspot.com
• 6. String Formatting ● C – printf() – sprintf() ● C++ <iomanip> – ● Python – string formatting is similar to Cwww.youtube.com/vkedco www.vkedco.blogspot.com
• 7. Basic Syntax ● format_str % values – format_str is a string to be formatted – % is a required operator – values specify formatting values – values must specify a value for every specifier that format_str contains.www.youtube.com/vkedco www.vkedco.blogspot.com
• 8. Formatting Specifiers ● Full (and rather lengthy) list of specifiers is at http://docs.python.org/library/stdtypes.html#string-formatting-operations ● Some common specifiers that you are likely to use in your programs are: – %d signed integer – %x unsigned hexadecimal – %f floating point decimal format – %s string (converted using str()) – %% a percent signwww.youtube.com/vkedco www.vkedco.blogspot.com
• 9. Example 01 >>> x, y = 20, 5 ## x is assigned 20, y is assigned 5 >>> "John is %d years old." % x John is 20 years old. >>> "John is %d years and %d months old." % (x, y) John is 20 years and 5 months old.www.youtube.com/vkedco www.vkedco.blogspot.com
• 10. Example 02 >>> a, b = 10, 50 >>> a 10 >>> b 50 >>> "%d is %d%% of %d" % (a, a/float(b)*100, b) 10 is 20% of 50www.youtube.com/vkedco www.vkedco.blogspot.com
• 11. Specifier Width ● Specifier width is optional ● The width specifies the minimum number of characters for the formatted value: >>> "%d" % 2 2 >>> "%2d" % 2 ### 2 characters wide 2 >>> "%3d" % 2 ### 3 characters wide 2www.youtube.com/vkedco www.vkedco.blogspot.com
• 12. Specifier Width ● The asterisk (*) is used to indicate that the width should be read from a tuple (this is a typical use of tuples) >>> "%*d" % (4, 2) 2 ● The above formatting instruction "%*d" % (4, 2) means: allocate 4 fields for the digit 2www.youtube.com/vkedco
• 13. Specifier Precision ● Specifier precision is optional ● Precision follows width and is preceded by a period ● You can use asterisk to get precision from a value tuple ● For numbers, precision specifies the number of decimals included in result ● For strings, precision specifies the maximum number of characterswww.youtube.com/vkedco www.vkedco.blogspot.com
• 14. Precision Examples >>> "%f" % 123.4567 ## 10 slots are allocated by default 123.456700 ## so two zeros are padded at the end >>> "%f" % 123.456789 123.456789 ## all ten slots are taken >>> "%.0f" % 123.456789 123 ## the decimal part is chopped off >>> "%.2f" % 123.456789 123.46 ## 2 decimal slots are preserved. Note the rounding >>> "%10.3f" % 12345.6789 12345.679 ## 10 slots before the decimal point and 3 after >>> "%2.3f" % 12345.6789 12345.679 ## we could not get 2 slots before the point.www.youtube.com/vkedco www.vkedco.blogspot.com
• 15. Precision Examples ## allocate a string of 10 characters and ## take 2 characters from night. >>> "%*.*s" % (10, 2, night) ni ## allocate a string of 10 characters and ## take 3 characters from night. >>> "%*.*s" % (10, 3, night) nig ## allocate a string of 5 characters and take 4 ## characters from night. >>> "%*.*s" % (5, 4, night) nighwww.youtube.com/vkedco www.vkedco.blogspot.com
• 16. Optional Conversion Flags ● The purpose of conversion flags is to convert a specific value before it is inserted into the format string ● A conversion flag, when present, must occur before width and precision ● Here are a few common conversion flags: dash (-), pound sign (#), zero (0), spacewww.youtube.com/vkedco www.vkedco.blogspot.com
• 17. Conversion Flags: Dash (-) ● The value is left adjusted ## no dash, so value is right adjusted by default. >>> "%4d" % 2 2 ## there is a dash, so value is left adjusted. >>> "%-4d" % 2 2 ## allocate 10 characters, take 2 characters from ## night and left adjust them. >>> "%-*.*s" % (10, 2, night) ni www.youtube.com/vkedco www.vkedco.blogspot.com
• 18. Conversion Flags: Pound (#) ● Convert the value according to the specification that follows # ## convert 17 into octal representation. >>> "%#o" % 17 021 ## convert 17 into hexadecimal representation. >>> "%#x" % 17 0x11www.youtube.com/vkedco www.vkedco.blogspot.com
• 19. Conversion Flags: Zero (0) ● Pad numerical values with 0s on the left >>> "%*d" % (10, 5) ## default behavior 5 >>> "%0*d" % (10, 5) ## allocate 10 slots and pad with 0s 0000000005 >>> "%*.*f" % (10, 2, 123.456789) ## default behavior 123.46 ## allocate 10 slots, take 2 numbers after the decimal ## point and pad the remaining left slots with 0s. >>> "%0*.*f" % (10, 2, 123.456789) 0000123.46www.youtube.com/vkedco www.vkedco.blogspot.com
• 20. Conversion Flags: Space ● A blank should be left before a positive number >>> "% d" % 3 3 >>> "% d" % -3 ## converts to empty string for ## negative numbers -3www.youtube.com/vkedco www.vkedco.blogspot.com
• 21. String Module ● To use the string module, execute import string ● In general, many methods can be called as functions of the string module (many of these are depricated) or as methods on string objects ● Calling methods on string objects is preferredwww.youtube.com/vkedco www.vkedco.blogspot.com
• 22. Functions vs. Object Methods >>> import string >>> string.upper("hello") ## depricated function, but still works HELLO >>> "hello".upper() ## preferred object method HELLO >>> x = " hello " >>> string.strip(x) ## depricated function, but still works hello >>> x hello >>> x.strip() ## preferred object method hellowww.youtube.com/vkedco www.vkedco.blogspot.com
• 23. String Module Constants ● The string module contains some useful constants – ascii_letters, ascii_lowercase, ascii_uppercase – digits, hexdigits, letters – lowercase, octdigits – punctuation, printable, uppercase, whitespace >>> import string >>> string.ascii_letters abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV WXYZ >>> string.punctuation !"#\$%&()*+,-./:;<=>?@[]^_`{|}~www.youtube.com/vkedco www.vkedco.blogspot.com
• 24. string.capwords() ● Some methods can only be called as the string module functions >>> s = "poetry, music, and math" >>> string.capwords(s) Poetry, Music, And Math >>> s.capwords() ## errorwww.youtube.com/vkedco www.vkedco.blogspot.com
• 25. String Building ● String building is turning a sequence (e.g. a list or a tuple) of characters into a string ● For example, start with this: [k, n, i, g, h, t] ● End with this: knightwww.youtube.com/vkedco www.vkedco.blogspot.com
• 26. Obvious Solution chars = [k, n, i, g, h, t] myStr = ## string to be built for ch in chars: ## loop thru chars myStr += ch ## print chars and myStr. print chars = , chars print myStr = , myStrwww.youtube.com/vkedco www.vkedco.blogspot.com
• 27. join() Solution >>> chars = [k, n, i, g, h, t] >>> myStr = .join(chars) >>> myStr knightwww.youtube.com/vkedco www.vkedco.blogspot.com
• 28. Comments on Obvious Solution ● Obvious solutions get the job done ● But, they are verbose ● We can solve both string building problems by using the join() methodwww.youtube.com/vkedco www.vkedco.blogspot.com
• 30. Object Comparison ● The operators <, >, ==, >=, <=, and != compare the values of two objects ● The objects need not have the same type ● If both are numbers, they are converted to a common type ● Objects of different types always compare unequal and are ordered consistently but arbitrarily: – (1) < [1] ### True – [1] < (1) ### Falsewww.youtube.com/vkedco www.vkedco.blogspot.com
• 31. Object Comparison ● Numbers are compared arithmetically ● Strings are compared lexicographically using the numeric equivalents of their characters ● Tuples and lists are compared lexicographically using comparison of corresponding elements ● Sequences, to compare equal, must be of the same type and have the same length and the corresponding elements must compare equal ● Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equalwww.youtube.com/vkedco www.vkedco.blogspot.com