Python Class Notes

You might also like

Download as pdf
Download as pdf
You are on page 1of 16
Pees See ron String Concatenation >>> a = 'Hello' >>> b = a+ 'There’ When the + operator is >>> print (b) applied to strings, it means HelloThere “concatenation” >>> c=a+t' ' + 'There' >>> print (c) Hello There Pood See Pees rong Using in as a Logical Operator ° The in keyword can also be used to check to see if one string is “in” another string ba aX Mla ->. okt EE] logical expression that returns [rue or False and can be used in an if statement >>> fruit = 'banana' be ae aE beast) poo EE Wes arent ce wit Poon COMMER Weare beat) oot ES ese a Pose A Rabat e aD) xen eRe aT pod Pero gae.g See ron String Comparison EE an (col porte tetany print('All right, bananas.') if word < 'banana': print('Your word,' + word + ', comes before banana.') elif word > 'banana': print('Your word,' + word + ', comes after banana.') CET print('All right, bananas.') See Python has a number of string SMR NCNM cS lao mn ole-lavg These functions are already built into every string - we invoke them by appending the function to the string variable These functions do not modify the original string, instead they return a new string that has Loli Pees ron String Library >>> greet = 'Hello Bob' >>> zap = greet.lower() >>> print (zap) hello bob >>> print (greet) Hello Bob >>> print('Hi There'.lower()) hi there booed real Garni >>> stuff = ‘Hello world' >>> type (stuff) >>> dir (stuff) ['capitalize', 'casefold', 'center', 'count', ‘encode’, Pesce ee Che Se SC oes Se ‘index', ‘isalnum', 'isalpha', 'isdecimal', ‘isdigit', ‘isidentifier', 'islower', '‘isnumeric', 'isprintable', 'isspace', ‘istitle', ‘isupper', ‘join', 'ljust', 'lower', 'lstrip', ‘maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', Pata aah) Mees) eee oe eS) eS Se ST Perth We se eo co esse baa] eeu ogy SU se ser-replace(old, new, count)) Return a copy ofthe string with all occurrences of substring old replaced by new: If the optional argument count is given, only the first count occurrences are replaced ser-rfind(subl, stard, endl) Return the highest index in the string where substring sub is found, such that sub Is contained within art send). Optional arguments startand end are interpreted asin slice notation. Retuen =1 on fallre. ser. rindex(sudl, star, endl) Like sind) but raises valuetcsor when the substring sub isnot found. oes just (wiht, flchar)) Return the string right justified in a string of length width, Padding Is done using the speciRed flehar (default is an ASC space). The original string is returned if width sles than or equal to 1en() scr xpartition(sep) Split the sting atthe last occurrence of sep, and return a 3-tuple containing the part before the separator, the Separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself. ste epLit sep-None, maxsplt=-1) Return alist of the words in the string, using sep as the delimiter string, If maxsplit is glven, at most maxsplit splits are done, the rightmost ones. If Sep Is not specified or fone, any whitespace string Is a separator. Except for spliting from the right, z=p1i+() behaves like ep1i¢;) which fs described in detail below. See Pees ron String Library str.capitalize() Sears ee seats TTB) str.endswith(suffix[, start[, end]]) PS oeeenCr Ome tad eT) Eeepeaee tC Cts 3B) str.replace(old, new[, count]) str.lower() str.rstrip([chars]) Piece see ts Cts 3B) str.upper() See Searching a String + We use the find() function to search for a substring within another string » find() finds the first occurrence of the substring + If the substring is not found, find() roa + Remember that string position starts at zero Pees ron ™~ 012345 >>> fruit = 'banana' poo esate arse (GEC as) poe a Skat olor) Py >>> aa = fruit.find('z') >>> print (aa) oe See Pees ron Making Everything UPPER CASE * You can make a copy of a string in lower case or upper oo 0) i (Tea NAR oe-ler- Lee) for a string using find() we first convert the string to lower case so we Can search a string regardless of case >>> greet = 'Hello Bob' >>> nnn = greet.upper() >>> print (nnn) HELLO BOB >>> www = greet.lower() boo ee hap) hello bob ae See Pees ron Search and Replace * The replace() function SMI Wt 1el DTA) replace” operation in a word processor iimgcle)t-le- eels Coleco iriure) AUNT) search string with the ye) lecular) >>> greet = 'Hello Bob! oo eee r ate Eo OS 1) MU ED) >>> print (nstr) Hello Jane >>> nstr = greet. replace('o','X') >>> print (nstr) BOB Dab) 4) >>> Pees See ron Stripping Whitespace * Sometimes we want to take bee Gee Sai eas" a string and remove Ea eee Al fi aaa ello Bol whitespace at the beginning eer and/or end a se en : : >>> greet.strip() ® \strip() and rstrip() remove "Hello Bob! whitespace at the left or right ea strip() removes both beginning and ending whitespace Pees See ron Prefixes >>> line = 'Please have a nice day' >>> line.startswith('Please') True >>> line.startswith('p') poe WET) Pero gae.g See ron Parsing and Extracting 21 | t t From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 poo pod poo Ail poo boos 31 boos poo poy data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' EAs MEL we SEK CRD) print (atpos) DN | sppos = data.find(' ',atpos) 4 are) host = data[atpos+l : sppos] NY portato) Eee See Pees ron Strings and Character Sets as ee) So ae) Ese >>> type (x) oe ae eo >>> type(x) Boast ME Kore poe a ee >>> x = 'O|2E' >>> type (x) >>> x = u' OBE" >>> type(x) coos In Python 3, all strings are Unicode Pees See ron Summary eS UUeAN2 * String operations + Read/Convert * String library + Indexing strings [] + String Comparisons * Slicing strings [2:4] * Searching in strings * Looping through strings + Replacing text with for and while * Stripping white space * Concatenating strings with + SUL eee Acknowledgements / Contributions “These slides are Copyright 2010- Charles R. Severance r ene eee ee eae phere) eee ne ene eee aT last slide in all copies of the document to comply with the ee ce ee ene tae ee ans eee een ee Pees Insert new Contributors and Translators here Pero gae.g ron

You might also like