Python & Perl  String Access & Modification, Perl List & Scalar   Contexts, Perl HERE Documents, User Input,             P...
Outline  ●   String Access & Modification  ●   Perl List & Scalar Contexts  ●   Perl HERE Documents  ●   User Input  ●   P...
String Access & Modification       source at substr_char_indexing.pl, substr_substring_manip.plwww.youtube.com/vkedco     ...
PY String Access     ●   Strings are immutable sequences, i.e. they         cannot be modified after they are created     ...
PY String Access     ●   Character access is done via 0-based index-         ing from the left and -1-based (that is -1) i...
PL String Access      my $str_01 = the sail just needs to open;      ## extract 3 characters from and including      ## po...
PL String Access      my $str_01 = the sail just needs to open;      ## extract 9 characters from and including      ## po...
PL String Access      my $str_01 = the sail just needs to open;      ## when the third argument is omitted,      ## it is ...
PL String Modification      my $str_01 = the sail just needs to open;      ## when the fourth argument is used it is the  ...
PL String Modification      my $str_02 = the sail just needs to open;      ## swallow s at the end of needs      substr($s...
Perl List & Scalar Contexts                 source at list_and_scalar_contexts.plwww.youtube.com/vkedco                www...
Context     ●   A context is a region of code where a specific         type is required for the program to complete       ...
List vs Scalar Contexts       my @lst_01 = (1, 2, 3, 4);       my $len = length(@lst_01); ## this is incorrect: the argume...
Scalar String vs Scalar Numeric       my $str = "5";       my $num = 5.7;       ## add a number to a string.       ## $str...
Scalar String vs Scalar Numeric       my $str = "5";       my $num       = 5.5;       ## $num is converted to a string in ...
Perl HERE Documents                   source at here_doc_examples.plwww.youtube.com/vkedco              www.vkedco.blogspo...
Perl Here-Documents   ●   A here-document allows you to write large       amounts of text in your program and treat them a...
Here-Document Syntax    print <<IDENTIFIER;    text line 01    text line 02    …    text line N    IDENTIFIERwww.youtube.c...
Here-Document Example    print <<EOT;    This is a line of text.    This is another line of text ...    Good bye.    EOTww...
User Input                 source at chop_chomp_examples.plwww.youtube.com/vkedco                 www.vkedco.blogspot.com
PY 2.X User Input   ●   There are two user input functions in Python:           –   input([prompt])           –   raw_inpu...
input() vs. raw_input()     >>> x = input("type in value for x: ")     type in value for x: 1 +     Traceback (most recent...
PY 2.X Documentation     input() “is not safe from user errors! It expects a valid     Python expression; if the input is ...
PL User Input   ●   The general Perl pattern of getting input from the       user is as follows:                my $user_i...
PL User Input & Functions chop(), chomp()   ●   Functions chop() & chomp() are frequently used       by Perl programmers t...
PL User Input & Functions chop(), chomp()   ●   chomp() is typically used to to remove       n at the end of user inputs  ...
chop() & chomp()     my @lst_01 = qw(the sail just needs to open);     print "@lst_01n";     ## chop() chops off the last ...
chop() & chomp()     my @lst_01 = qw(the sail just needs to open);     print "@lst_01n";     ## this illustrates that chop...
chop() vs chomp()     my @lst_02 = qw(the sail just needs to open);     print "@lst_02n";     ## does not remove any chara...
PL User Input & chomp()     ## chomp() is frequently used to chomp the newline off the user input.     ## this asks the us...
Python String Formattingwww.youtube.com/vkedco   www.vkedco.blogspot.com
PY Formatting Strings     ●   format_str % values           –   format_str is a string to be formatted           –   % is ...
Formatting Specifiers     ●   Full list of specifiers is at         http://docs.python.org/library/stdtypes.html#string-fo...
PY Formatting Specifiers: Example     >>> x, y = 20, 5     >>> "John is %d years old." % x     John is 20 years old.     >...
PY Specifying Width     ●   Specifier width is optional     ●   The width specifies the minimum number of         characte...
PY Specifier Width    ●   The asterisk (*) is used to indicate that the        width should be read from a tuple.        >...
PY Precision Examples      >>> "%f" % 123.4567 ## 10 slots are allocated by default      123.456700 ## so two zeros are pa...
PY Precision Examples      >>> "%10.3f" % 12345.6789  ●   We want to assign 10 slots before the decimal point and 3 after ...
PY Precision Examples    ## allocate a string of 10 characters and take 2 characters from night    >>> "%*.*s" % (10, 2, n...
PY String Module    ●   To use the string module, execute            import string    ●   In general, many methods can be ...
PY Functions vs. Object Methods      >>> import string      >>> string.upper("hello")   ## depricated, but still works.   ...
Example: string.capwords()    ●   Some methods can only be called as        the string module functions        >>> s = "po...
References  ●   www.python.org  ●   http://docs.python.org/2/  ●   www.perl.org  ●   http://perldoc.perl.org/www.youtube.c...
Upcoming SlideShare
Loading in …5
×

Python & Perl: String Access & Modification; Perl List & Scalar Contexts; Perl HERE Documents; User Input; Python String Formatting

899 views

Published on

Python & Perl: String Access & Modification; Perl List & Scalar Contexts; Perl HERE Documents; User Input; Python String Formatting

Published in: Software
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
899
On SlideShare
0
From Embeds
0
Number of Embeds
561
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Python & Perl: String Access & Modification; Perl List & Scalar Contexts; Perl HERE Documents; User Input; Python String Formatting

  1. 1. Python & Perl String Access & Modification, Perl List & Scalar Contexts, Perl HERE Documents, User Input, Python String Formatting Vladimir Kulyukinwww.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Outline ● String Access & Modification ● Perl List & Scalar Contexts ● Perl HERE Documents ● User Input ● Python String Formattingwww.youtube.com/vkedco www.vkedco.blogspot.com
  3. 3. String Access & Modification source at substr_char_indexing.pl, substr_substring_manip.plwww.youtube.com/vkedco www.vkedco.blogspot.com
  4. 4. PY String Access ● Strings are immutable sequences, i.e. they cannot be modified after they are created >>> x = [1, 2, 3] >>> x[1] = 5555 # this is OK, x is a list >>> y = (1, 2, 3) >>> y[1] = 9999 # error, y is a tuple >>> z = spam >>> z[1] = P # error, z is a stringwww.youtube.com/vkedco www.vkedco.blogspot.com
  5. 5. PY String Access ● Character access is done via 0-based index- ing from the left and -1-based (that is -1) in- dexing from the right ● Slices can be taken as well >>> x = abc >>> x[1] == b ## 1st character from left >>> x[-1] == c ## 1st character from right >>> x[1:] == bc ## a slice from 1 to endwww.youtube.com/vkedco www.vkedco.blogspot.com
  6. 6. PL String Access my $str_01 = the sail just needs to open; ## extract 3 characters from and including ## position 0, i.e., characters in postions ## 0, 1, and 2. my $sub_str_01 = substr($str_01, 0, 3); ## prints the print "substr($str_01, 0, 3) = $sub_str_01n";www.youtube.com/vkedco www.vkedco.blogspot.com
  7. 7. PL String Access my $str_01 = the sail just needs to open; ## extract 9 characters from and including ## postion 4, i.e., characters in positions ## from 4 upto 12. my $sub_str_02 = substr($str_01, 4, 9); print "substr($str_01, 4, 9) = $sub_str_02n";www.youtube.com/vkedco www.vkedco.blogspot.com
  8. 8. PL String Access my $str_01 = the sail just needs to open; ## when the third argument is omitted, ## it is assumed to be the end of the string. my $sub_str_03 = substr($str_01, 4); print "substr($str_01, 4) = $sub_str_03n";www.youtube.com/vkedco www.vkedco.blogspot.com
  9. 9. PL String Modification my $str_01 = the sail just needs to open; ## when the fourth argument is used it is the ## replacement that replaces the ## characters from offset and upto offset+length-1 ## in string. the string is destructively modified. substr($str_01, 4, 4, sky); ## prints out the sky just needs to open print "$str_01n";www.youtube.com/vkedco www.vkedco.blogspot.com
  10. 10. PL String Modification my $str_02 = the sail just needs to open; ## swallow s at the end of needs substr($str_02, 18, 1, ); print "$str_02n"; ## prints the sail just need to open ## insert sky and at position 4. substr($str_02, 4, 0, sky and ); ## prints the sky and sail just need to open print "$str_02n";www.youtube.com/vkedco www.vkedco.blogspot.com
  11. 11. Perl List & Scalar Contexts source at list_and_scalar_contexts.plwww.youtube.com/vkedco www.vkedco.blogspot.com
  12. 12. Context ● A context is a region of code where a specific type is required for the program to complete its task ● - In Perl, two context types are distinguished: list & scalar ● The scalar context type can be sub-divided into, we need the string context and the nu- meric contextwww.youtube.com/vkedco www.vkedco.blogspot.com
  13. 13. List vs Scalar Contexts my @lst_01 = (1, 2, 3, 4); my $len = length(@lst_01); ## this is incorrect: the argument ## to length must be a scalar. print $len, "n"; ## @lst_01 is converted to its length in scalar numeric context my $x = @lst_01; ## numeric context. print $x, "n"; ## is is @lst_01s length my @y = @lst_01; ## list context print "@yn"; print "@lst_01n";www.youtube.com/vkedco www.vkedco.blogspot.com
  14. 14. Scalar String vs Scalar Numeric my $str = "5"; my $num = 5.7; ## add a number to a string. ## $str is converted to a number in the numeric ## context. $sum = 5.7 + 5 = 10.7 my $sum = $num + $str; ## . is the string concatentation operator print Adding $num and $str: . $sum . "n";www.youtube.com/vkedco www.vkedco.blogspot.com
  15. 15. Scalar String vs Scalar Numeric my $str = "5"; my $num = 5.5; ## $num is converted to a string in the ## string context. my $concat = $num . $str; ## string concatenation ## this prints 5.55 print Concatenation of $num and $str: . $concat . "n";www.youtube.com/vkedco www.vkedco.blogspot.com
  16. 16. Perl HERE Documents source at here_doc_examples.plwww.youtube.com/vkedco www.vkedco.blogspot.com
  17. 17. Perl Here-Documents ● A here-document allows you to write large amounts of text in your program and treat them as strings ● A here-document starts with << immediately followed (no white space!) by a start label, then some text, and a terminating label that must be the same as the start label ● The terminating label must be on a separate line by itself with no semicolonwww.youtube.com/vkedco www.vkedco.blogspot.com
  18. 18. Here-Document Syntax print <<IDENTIFIER; text line 01 text line 02 … text line N IDENTIFIERwww.youtube.com/vkedco www.vkedco.blogspot.com
  19. 19. Here-Document Example print <<EOT; This is a line of text. This is another line of text ... Good bye. EOTwww.youtube.com/vkedco www.vkedco.blogspot.com
  20. 20. User Input source at chop_chomp_examples.plwww.youtube.com/vkedco www.vkedco.blogspot.com
  21. 21. PY 2.X User Input ● There are two user input functions in Python: – input([prompt]) – raw_input([prompt]) ● Similarities – Both take an optional prompt – Both read user input ● Differences – input() reads an input string as a Python expression and evaluates it – raw_input() returns the input as a stringwww.youtube.com/vkedco www.vkedco.blogspot.com
  22. 22. input() vs. raw_input() >>> x = input("type in value for x: ") type in value for x: 1 + Traceback (most recent call last): File "<pyshell#37>", line 1, in <module> x = input("type in value for x: ") File "<string>", line 1 1+ ^ SyntaxError: unexpected EOF while parsing >>> x = raw_input("type in value for x: ") type in value for x: 1 + >>> x 1 + www.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. PY 2.X Documentation input() “is not safe from user errors! It expects a valid Python expression; if the input is not syntactically valid, a SynaxError will be raised. Other exceptions may be raised if there is an error during evaluation... Consider using raw_input() function for general input from users.” http://docs.python.org/library/functions.html#inputwww.youtube.com/vkedco www.vkedco.blogspot.com
  24. 24. PL User Input ● The general Perl pattern of getting input from the user is as follows: my $user_input = <STDIN>; ● This operation reads user input from <STDIN> (standard input stream) and places it (scalar string) into the scalar variable $user_inputwww.youtube.com/vkedco www.vkedco.blogspot.com
  25. 25. PL User Input & Functions chop(), chomp() ● Functions chop() & chomp() are frequently used by Perl programmers to proccess user input ● chop() destructively removes the last character in the string regardless of what that character is ● chomp() also destructively removes the last character of the string if and only if that character happens to match the value of the special character $/ - the input record separator ● $/ defaults to n on many systemswww.youtube.com/vkedco www.vkedco.blogspot.com
  26. 26. PL User Input & Functions chop(), chomp() ● chomp() is typically used to to remove n at the end of user inputs ● Both chop() & chomp() work on individual strings as well as lists of strings ● Absent any arguments, both work on $_www.youtube.com/vkedco www.vkedco.blogspot.com
  27. 27. chop() & chomp() my @lst_01 = qw(the sail just needs to open); print "@lst_01n"; ## chop() chops off the last character of each string in ## @lst_01 chop(@lst_01); ## this prints th sai jus need t ope print "@lst_01n";www.youtube.com/vkedco www.vkedco.blogspot.com
  28. 28. chop() & chomp() my @lst_01 = qw(the sail just needs to open); print "@lst_01n"; ## this illustrates that chop() executes in the ## scalar string context: $x is converted to 12 ## and then 2 is chopped off. my $x = 12; chop($x); print "$xn";www.youtube.com/vkedco www.vkedco.blogspot.com
  29. 29. chop() vs chomp() my @lst_02 = qw(the sail just needs to open); print "@lst_02n"; ## does not remove any characters because the strings in ## @lst_02 do not end with n chomp(@lst_02); print "@lst_02n"; my @list_03 = ("then", "sailn", "justn", "needsn", "ton", "openn"); print "@list_03n"; chomp(@list_03); ## chomp() removes n in each string print "@list_03n";www.youtube.com/vkedco www.vkedco.blogspot.com
  30. 30. PL User Input & chomp() ## chomp() is frequently used to chomp the newline off the user input. ## this asks the user to enter two scalars, chomps off the newline and ## returns their sum in the scalar numeric context. print Input a number: ; my $x1 = <STDIN>; chomp($x1); print Input a number: ; my $x2 = <STDIN>; chomp($x2); print $x1 + $x2, "n";www.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. Python String Formattingwww.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. PY Formatting Strings ● 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 containswww.youtube.com/vkedco www.vkedco.blogspot.com
  33. 33. Formatting Specifiers ● Full list of specifiers is at http://docs.python.org/library/stdtypes.html#string-formatting- operations ● Some common specifiers – %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
  34. 34. PY Formatting Specifiers: Example >>> x, y = 20, 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
  35. 35. PY Specifying Width ● Specifier width is optional ● The width specifies the minimum number of characters for the formatted value >>> "%d" % 2 2 >>> "%2d" % 2 2 >>> "%3d" % 2 2www.youtube.com/vkedco www.vkedco.blogspot.com
  36. 36. PY Specifier Width ● The asterisk (*) is used to indicate that the width should be read from a tuple. >>> "%*d" % (4, 2) 2 ● The formatting instruction “%*d” % (4, 2) means allocate four fields for the digit 2www.youtube.com/vkedco www.vkedco.blogspot.com
  37. 37. PY Precision Examples >>> "%f" % 123.4567 ## 10 slots are allocated by default 123.456700 ## so two zeros are padded at the end >>> "%.2f" % 123.456789 123.46 ## 2 decimal slots are preserved. Note ## the rounding of 5 to 6 >>> "%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 pointwww.youtube.com/vkedco www.vkedco.blogspot.com
  38. 38. PY Precision Examples >>> "%10.3f" % 12345.6789 ● We want to assign 10 slots before the decimal point and 3 after ● This cannot be done, because there are only 5 digits to the left of the decimal point ● So, three slots are assigned after the decimal point and all digits to the left of decimal points are placed to the left of decimal point ● This leaves us one space, which is padded to the left. So the output is: 12345.679www.youtube.com/vkedco www.vkedco.blogspot.com
  39. 39. PY 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 & 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
  40. 40. PY String Module ● To use the string module, execute import string ● In general, many methods can be called as functions of the string module or as methods on string objects ● Calling methods on string objects is preferred whenever possible ● Caveat: some methods in the string module are depreciatedwww.youtube.com/vkedco www.vkedco.blogspot.com
  41. 41. PY Functions vs. Object Methods >>> import string >>> string.upper("hello") ## depricated, but still works. HELLO >>> "hello".upper() ## preferred, returns a new string HELLO >>> x = " hello " >>> string.strip(x) ## depricated, but still works. hello >>> x hello >>> x.strip() ## preferred, returns a new string hellowww.youtube.com/vkedco www.vkedco.blogspot.com
  42. 42. Example: 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
  43. 43. References ● www.python.org ● http://docs.python.org/2/ ● www.perl.org ● http://perldoc.perl.org/www.youtube.com/vkedco www.vkedco.blogspot.com

×