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

Slides:



Advertisements
Similar presentations
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Advertisements

The Binary Numbering Systems
Numbers. Number data types store numeric values They are immutable data types, which means that changing the value of a number data type results in a.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Strings, if/else, return, user input
1 Python Chapter 3 Reading strings and printing. © Samuel Marateck.
Bit Operations C is well suited to system programming because it contains operators that can manipulate data at the bit level –Example: The Internet requires.
A bit can have one of two values: 0 or 1. The C language provides four operators that can be used to perform bitwise operations on the individual bits.
8. Python - Numbers Number data types store numeric values. They are immutable data types, which means that changing the value of a number data type results.
Strings. Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
4. Python - Basic Operators
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Computers Organization & Assembly Language
 2005 Pearson Education, Inc. All rights reserved Formatted Output.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 8 More on Strings and Special Methods 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Python for Informatics: Exploring Information
Input, Output, and Processing
Basic Operators. What is an operator? using expression is equal to 9. Here, 4 and 5 are called operands and + is the operator Python language supports.
CSE1222: Lecture 2The Ohio State University1. mathExample2.cpp // math example #include using namespace std; int main() { cout
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Instructor: Craig Duckett Lecture 08: Thursday, October 22 nd, 2015 Patterns, Order of Evaluation, Concatenation, Substrings, Trim, Position 1 BIT275:
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 5 Strings CSC1310 Fall Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 3 Mathematical Functions, Strings, and Objects.
More Strings CS303E: Elements of Computers and Programming.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
5 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
If/else, return, user input, strings
Chapter 4 Numbers CSC1310 Fall Python Program Structure import math r=int(raw_input()) print 4.0/3*math.pi*r**3 volume.py: Program Program Module.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
LECTURE 5 Strings. STRINGS We’ve already introduced the string data type a few lectures ago. Strings are subtypes of the sequence data type. Strings are.
CS 201 California State University, Los Angeles.  Various Mathematical Functions  Characters  Strings.
INTRO2CS Tirgul 4 1. What will we see today?  Strings  Lists  Tuples  Mutable and Immutable  Iterating over sequences  Nested Loops  Shallow and.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CS 100: Roadmap to Computing
String Processing Upsorn Praphamontripong CS 1110
Strings Part 1 Taken from notes by Dr. Neil Moore
Formatting Output.
Winter 2018 CISC101 11/16/2018 CISC101 Reminders
Basic Python Collective variables (sequences) Lists (arrays)
Arithmetic operations, decisions and looping
Chapter 8 More on Strings and Special Methods
Chapter 8 More on Strings and Special Methods
Python - Strings.
Chapter 8 More on Strings and Special Methods
CS 100: Roadmap to Computing
CSC 221: Introduction to Programming Fall 2018
Chapter 3 Mathematical Functions, Strings, and Objects
Fundamentals of Python: First Programs
CHAPTER 3: String And Numeric Data In Python
CS 1111 Introduction to Programming Spring 2019
590 Scraping – NER shape features
Topics Basic String Operations String Slicing
Introduction to Computer Science
Topics Basic String Operations String Slicing
CS 100: Roadmap to Computing
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Topics Basic String Operations String Slicing
STRING MANUPILATION.
Presentation transcript:

Python Crash Course strings, math 3 rd year Bachelors V1.0 dd 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!' >>> 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' # 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] # ?

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

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 >>>

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“)

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

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

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

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.)

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) >>> d = {'web': 'user', 'page': 42} >>> ' ' >>> 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']

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'

Converting strings and numbers >>> # Numbers to strings: >>> str(123), str(2**1000) >>> str(1.e10), str(1.+2j) >>> # Strings to numbers: >>> int("123"), int(" "*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’

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( , 2) # negative precision allowed Comparisons: >>> 5 * 2 == True >>> 0.12 * 2 == False >>> a = 0.12 * 2; b = >>> eps = >>> a - eps < b < a + eps True

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 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.

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:

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 |Binary OR Operator copies a bit if it exists in eather operand. (a | b) will give 61 which is ^Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49 which is ~Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~a ) will give -60 which is <<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 >>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 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 = b = a&b = a|b = a^b = ~a = There are following Bitwise operators supported by Python language

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:

Number formatting >>> print "Today's stock price: %f" % >>> print "Today's stock price: %.2f" % >>> print "Change since yesterday: %+.2f" % >>> "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 * ) 'Total with tax: $14.07' >>> d = {'web': 'user', 'page': 42} >>> ' % d '

Logical Operators End