Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Crash Course strings, math 3 rd year Bachelors V1.0 dd 02-09-2013 Hour 7.

Similar presentations


Presentation on theme: "Python Crash Course strings, math 3 rd year Bachelors V1.0 dd 02-09-2013 Hour 7."— Presentation transcript:

1 Python Crash Course strings, math 3 rd year Bachelors V1.0 dd 02-09-2013 Hour 7

2 Introduction to language - strings >>> 'spam and eggs' 'spam and eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't" >>> '"Yes," he said.' '"Yes," he said' >>> hello = 'Greetings!' >>> hello 'Greetings!' >>> print(hello) Greetings! >>> print(hello + ' How do you do?') Greetings! How do you do? >>> print(hello, 'How do you do?') Greetings! How do you do? >>> howdo = 'How do you do?' >>> print(hello+' '+howdo) Greetings! How do you do? >>> s = "GMRT is a telescope!" # Assignment >>> len(s) # Length; no trailing NULL >>> "gmrt" + "gmrt" # Concatination >>> 'gmrt' + "gmrt" >>> 'gmrt' + 100 # No automatic conversion, won’t work >>> 'gmrt' + ’100’ >>> 'gmrt' * 100 >>> 'gmrt' * ’100’ >>> s = "GMRT is a radio telescope!" >>> s[0] # First character >>> s[1] # Second character >>> s[100] # Bounds are checked! >>> s[-1] # ?

3 Introduction to language - strings triple-quotes (docstrings) In [12]: usage = """....: Usage: thingy [OPTIONS]....: -h Display this usage message....: -H hostname Hostname to connect to....: """ In [14]: usage Out[15]: '\nUsage: thingy [OPTIONS]\n -h Display this usage message\n -H hostname Hostname to connect to\n' In [15]: print usage Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to

4 Introduction to language - strings raw string In [1]: hello = r"This is a rather long string containing\n\...: several lines of text much as you would do in C." In [2]: In [2]: print hello This is a rather long string containing\n\ several lines of text much as you would do in C. >>> hello = "asdasd\... adasda" >>> print hello asdasdadasda >>>

5 Introduction to language - slicing >>> s = "GMRT is a radio telescope!" >>> s[2:5] # Includes s[2], but not s[5] >>> s[5:2] # Empty string >>> s[2:2] # again empty >>> s[5:-1] # Excludes last character >>> s[-100:100] # Bounds are ignored here >>> s[:5] # Default first index: 0 >>> s[5:] # Default last index: len(s) >>> s[:] # Copy of complete string >>> s[2:10:2] >>> s[::-1] >>> s = "GMRT works great!" >>> s[5] = "F" # Strings are immutable! >>> s = s[:5] + "F" + s[6:] >>> s.replace("great", "poorly") >>> print s # s is unchanged! >>> s = s.replace("great", "poorly") Object oriented programming creeping in: >>> " Hello world ".strip() >>> s = "GMRT is in Khodad!" >>> s.split() # List of strings >>> s = "GMRT\tis\nin Khodad!" >>> s.split() >>> s.split("o“)

6 String Methods SNMethods with Description 1capitalize() capitalize() Capitalizes first letter of string 2center(width, fillchar) center(width, fillchar) Returns a space-padded string with the original string centered to a total of width columns 3count(str, beg= 0,end=len(string)) count(str, beg= 0,end=len(string)) Counts how many times str occurs in string, or in a substring of string if starting index beg and ending index end are given 3decode(encoding='UTF-8',errors='strict') decode(encoding='UTF-8',errors='strict') Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. 4encode(encoding='UTF-8',errors='strict') encode(encoding='UTF-8',errors='strict') Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'. 5endswith(suffix, beg=0, end=len(string)) endswith(suffix, beg=0, end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; Returns true if so, and false otherwise 6expandtabs(tabsize=8) expandtabs(tabsize=8) Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided 7find(str, beg=0 end=len(string)) find(str, beg=0 end=len(string)) Determine if str occurs in string, or in a substring of string if starting index beg and ending index end are given; returns index if found and -1 otherwise 8index(str, beg=0, end=len(string)) index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found SNMethods with Description 9isa1num() isa1num() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise 10isalpha() isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise 11isdigit() isdigit() Returns true if string contains only digits and false otherwise 12islower() islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise 13isnumeric() isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise 14isspace() isspace() Returns true if string contains only whitespace characters and false otherwise 15istitle() istitle() Returns true if string is properly "titlecased" and false otherwise 16isupper() isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise 17join(seq) join(seq) Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string 18len(string) len(string) Returns the length of the string

7 String Methods SNMethods with Description 19ljust(width[, fillchar]) ljust(width[, fillchar]) Returns a space-padded string with the original string left-justified to a total of width columns 20lower() lower() Converts all uppercase letters in string to lowercase 21lstrip() lstrip() Removes all leading whitespace in string 22maketrans() maketrans() Returns a translation table to be used in translate function. 23max(str) max(str) Returns the max alphabetical character from the string str 24min(str) min(str) Returns the min alphabetical character from the string str 25replace(old, new [, max]) replace(old, new [, max]) Replaces all occurrences of old in string with new, or at most max occurrences if max given 26rfind(str, beg=0,end=len(string)) rfind(str, beg=0,end=len(string)) Same as find(), but search backwards in string 27rindex( str, beg=0, end=len(string)) rindex( str, beg=0, end=len(string)) Same as index(), but search backwards in string 28rjust(width,[, fillchar]) rjust(width,[, fillchar]) Returns a space-padded string with the original string right-justified to a total of width columns. 29rstrip() rstrip() Removes all trailing whitespace of string 30split(str="", num=string.count(str)) split(str="", num=string.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given SNMethods with Description 31splitlines( num=string.count('\n')) splitlines( num=string.count('\n')) Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed 32startswith(str, beg=0,end=len(string)) startswith(str, beg=0,end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; Returns true if so, and false otherwise 33strip([chars]) strip([chars]) Performs both lstrip() and rstrip() on string 34swapcase() swapcase() Inverts case for all letters in string 35title() title() Returns "titlecased" version of string, that is, all words begin with uppercase, and the rest are lowercase 36translate(table, deletechars="") translate(table, deletechars="") Translates string according to translation table str(256 chars), removing those in the del string 37upper() upper() Converts lowercase letters in string to uppercase 38zfill (width) zfill (width) Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero) 39isdecimal() isdecimal() Returns true if a unicode string contains only decimal characters and false otherwise

8 Escape characters Backslash notation Hexadecimal character Description \a0x07Bell or alert \b0x08Backspace \cx Control-x \C-x Control-x \e0x1bEscape \f0x0cFormfeed \M-\C-x Meta-Control-x \n0x0aNewline \nnn Octal notation, where n is in the range 0.7 \r0x0dCarriage return \s0x20Space \t0x09Tab \v0x0bVertical tab \x Character x \xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

9 String formatting One of Python's coolest features is the string format operator %. print "My name is %s and height is %d cm!" % ('Erik', 178) SymbolConversion %ccharacter %sstring conversion via str() prior to formatting %isigned decimal integer %dsigned decimal integer %uunsigned decimal integer %ooctal integer %xhexadecimal integer (lowercase letters) %Xhexadecimal integer (UPPERcase letters) %eexponential notation (with lowercase 'e') %Eexponential notation (with UPPERcase 'E') %ffloating point real number %gthe shorter of %f and %e %Gthe shorter of %f and %E SymbolFunctionality *argument specifies width or precision -left justification +display the sign leave a blank space before a positive number #add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used. 0pad from left with zeros (instead of spaces) %'%' leaves you with a single literal '%' (var)mapping variable (dictionary arguments) m.n.m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

10 str.format() string module formatting format() being a function, it can be used as argument in other functions: >>> "Name: {0}, age: {1}".format('John', 35) 'Name: John, age: 35' >>> tu = (12,45,22222,103,6) >>> print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu) 12 22222 45 22222 103 22222 6 22222 >>> d = {'web': 'user', 'page': 42} >>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) 'http://xxx.yyy.zzz/user/42.html‘ >>> li = [12,45,78,784,2,69,1254,4785,984] >>> print map('the number is {}'.format,li) ['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']

11 Unicode strings Unicode has the advantage of providing one ordinal for every character in every script used in modern and ancient texts. Previously, there were only 256 possible ordinals for script characters. In [22]: u'Hi' Out[22]: u'Hi' In [23]: u'Hè' Out[23]: u'H\ufffd‘ In [24]: s = u'Hè' In [25]: str(s) --------------------------------------------------------------------------- UnicodeEncodeError Traceback (most recent call last) in () ----> 1 str(s) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 1: ordinal not in range(128) In [26]: u'Hè'.encode('utf-8') Out[26]: 'H\xef\xbf\xbd'

12 Converting strings and numbers >>> # Numbers to strings: >>> str(123), str(2**1000) >>> str(1.e10), str(1.+2j) >>> # Strings to numbers: >>> int("123"), int("1234567890"*100) >>> float("1.23"), float("1.23e10") >>> float("1.23 e10") # Error >>> "123".isdigit() >>> "1.23".isdigit() # :-( very similar to sprintf in C >>> import math >>> s = "%s is %10.3g" % ("Pi", math.pi) >>> print s Riddle: what would the following produce? >>> var1 = ’hello’ >>> ’o’.join((var1.title().swapcae().split(’E’)))[0:-1] + ’w’

13 Introduction to language – math Functions: >>> abs(-2.) >>> abs(1+1j) >>> max(1,2,3,4) >>> min(1,2,3,4) >>> hex(17), oct(-5) >>> round(1.23456, 2) # negative precision allowed Comparisons: >>> 5 * 2 == 4 + 6 True >>> 0.12 * 2 == 0.1 + 0.14 False >>> a = 0.12 * 2; b = 0.1 + 0.14 >>> eps = 0.0001 >>> a - eps < b < a + eps True

14 Mathematical and Trigonometric Functions FunctionReturns ( description ) abs(x)The absolute value of x: the (positive) distance between x and zero. ceil(x)The ceiling of x: the smallest integer not less than x cmp(x, y)-1 if x y exp(x)The exponential of x: e x fabs(x)The absolute value of x. floor(x)The floor of x: the largest integer not greater than x log(x)The natural logarithm of x, for x> 0 log10(x)The base-10 logarithm of x for x> 0. max(x1, x2,...) The largest of its arguments: the value closest to positive infinity min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity modf(x)The fractional and integer parts of x in a two- item tuple. Both parts have the same sign as x. The integer part is returned as a float. pow(x, y)The value of x**y. round(x [,n])x rounded to n digits from the decimal point. Python rounds away from zero as a tie- breaker: round(0.5) is 1.0 and round(-0.5) is - 1.0. sqrt(x)The square root of x for x > 0 FunctionDescription acos(x)Return the arc cosine of x, in radians. asin(x)Return the arc sine of x, in radians. atan(x)Return the arc tangent of x, in radians. atan2(y, x)Return atan(y / x), in radians. cos(x)Return the cosine of x radians. hypot(x, y)Return the Euclidean norm, sqrt(x*x + y*y). sin(x)Return the sine of x radians. tan(x)Return the tangent of x radians. degrees(x)Converts angle x from radians to degrees. radians(x)Converts angle x from degrees to radians.

15 Comparson operators OperatorDescriptionExample ==Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true. !=Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true. <>Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a <> b) is true. This is similar to != operator. >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true. <Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true. >=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true. <=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true. Assume variable a holds 10 and variable b holds 20 then:

16 Bitwise Operators OperatorDescriptionExample &Binary AND Operator copies a bit to the result if it exists in both operands. (a & b) will give 12 which is 0000 1100 |Binary OR Operator copies a bit if it exists in eather operand. (a | b) will give 61 which is 0011 1101 ^Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49 which is 0011 0001 ~Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~a ) will give -60 which is 1100 0011 <<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. a << 2 will give 240 which is 1111 0000 >>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15 which is 0000 1111 Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 There are following Bitwise operators supported by Python language

17 Logical Operators OperatorDescriptionExample andCalled Logical AND operator. If both the operands are true then then condition becomes true. (a and b) is true. orCalled Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (a or b) is true. notCalled Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. not(a and b) is false. Assume variable a holds 10 and variable b holds 20 then:

18 Number formatting >>> print "Today's stock price: %f" % 50.4625 50.462500 >>> print "Today's stock price: %.2f" % 50.4625 50.46 >>> print "Change since yesterday: %+.2f" % 1.5 +1.50 >>> "Name: %s, age: %d" % ('John', 35) 'Name: John, age: 35' >>> i = 45 >>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) 'dec: 45/oct: 055/hex: 0X2D' >>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41) 'MM/DD/YY = 12/07/41' >>> 'Total with tax: $%.2f' % (13.00 * 1.0825) 'Total with tax: $14.07' >>> d = {'web': 'user', 'page': 42} >>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d 'http://xxx.yyy.zzz/user/42.html'

19 Logical Operators End


Download ppt "Python Crash Course strings, math 3 rd year Bachelors V1.0 dd 02-09-2013 Hour 7."

Similar presentations


Ads by Google