1 / 19

Python Crash Course strings, math

Python Crash Course strings, math. 3 rd year Bachelors V1.0 dd 02-09-2013 Hour 7. 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!'

akando
Download Presentation

Python Crash Course strings, math

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python Crash Coursestrings, math 3rd 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. Introductiontolanguage - 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. Introductiontolanguage - 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] 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“) >>> 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")

  6. String Methods

  7. String Methods

  8. Escape characters

  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)

  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) <ipython-input-28-d22ffcdd2ee9> in <module>() ----> 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 andTrigonometricFunctions

  15. Comparson operators Assume variable a holds 10 and variable b holds 20 then:

  16. Bitwise Operators There are following Bitwise operators supported by Python language 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

  17. Logical Operators Assume variable a holds 10 and variable b holds 20 then:

  18. Numberformatting >>> 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. LogicalOperators End

More Related