Introduction to Computing Using Python
Methods – on strings and other things
Strings, revisitedObjects and their methodsIndexing and slicingSome commonly used string methods
Introduction to Computing Using Python
Remember: What is a string?
A string is a sequence of zero or more charactersA string is delimited(begins andends) by singleor double quotespoem = 'Odeto a Nightingale'lyric = "Rollon, Columbia, roll on"exclamation = "Thatmakes me!#?"The empty string haszero characters (''or"")
Introduction to Computing Using Python
Quote characters in strings
You can include a single quote in a double quoted string or a double quote in a single quoted stringwill = "All the world's a stage"ben= 'BF: "A penny saved is a penny earned"'To put asingle quote in asinglequotedstring, precede it with the backslash ('\') or 'escape' character.>>> will = 'All the world\'s a stage'>>> print(will)Alltheworld'sa stageThe same goes for double quotes>>> ben = "BF:\"A penny saved is a penny earned\"">>> print(ben)BF:"A penny saved is a pennyearned"
Introduction to Computing Using Python
Putting a format character in a string
A format character is interpreted by the print() function to change the layout of textTo put a format character in a string, precede it with the backslash ('\')A newline is represented by '\n'>>>juliette= 'Good night, good night\nPartingis such sweet sorrow'>>> print(juliette)Good night, goodnightPartingis such sweet sorrowAtabis represented by'\t'>>> tabs ='col0\tcol1\tcol2'>>>print(tabs)col0col1col2
Introduction to Computing Using Python
Index of string characters
The first character of a string has index 0>>> greeting = 'hello, world'>>> greeting[0]'h'>>> 'hello, world'[0]'h'You can also count back from the end of a string, beginning with -1>>> greeting = 'hello, world'>>> greeting[-1]'d'>>> 'hello, world'[-1]'d'
Introduction to Computing Using Python
Slicing a string
You can use indexes to slice (extract a piece of) a stringaStr[i:j]is the substring that beginswithindexiandendswith(but does not include)index j>>> greeting = 'hello, world'>>> greeting[1:3]'el'>>> greeting[-3:-1]'rl'omit begin or end to mean 'as far as you can go'>>>print(greeting[:4], greeting[7:])hell worldaStr[i:j:k] is the same, but takes only every k-thcharacter>>> greeting[3:10:2]'l,wr'
Introduction to Computing Using Python
Index/slice a string vs index/slice a listHow they're the same and how they're different
SAME:You can index a list or string by providing an integer index value, beginning with 0 from the left or -1 from the right [i].Youcanslice a list or string by providing begin and end values ([i:j]) or begin, end and step values ([i:j:k])You can omitbeginor end ([:j] or [i:]) to mean 'as far as you can go'
Introduction to Computing Using Python
Listindexvs string index (continued)
DIFFERENT:if you reference a single element of a list with the index operator ([i]), itstype isthetype of thatelement>>>abc= ['a', 'b', 'c']>>>abc[0]'a'>>> type(abc[0])<class 'str'>If youslice(extracta pieceof)alist with begin and end ([i:j]) values, you get asublist(type list)>>>abc[0:2]['a', 'b']>>>type(abc[0:2])<class'list'>
Introduction to Computing Using Python
String methods
A method is a functionthatisbundled together with a particular type ofobjectA string method is a function that works on astringThis is the syntax of a method:anObject.methodName(parameterList)For example,>>> 'avocado'.index('a')0returnsthe index of the first 'a' in'avocado'Youcan alsouse avariable of type string>>> fruit='avocado'>>>fruit.index('a')0
Introduction to Computing Using Python
Method parameters
Like any function, a methodhas zeroor more parametersEven ifthe parameter list is empty, the method still works on the 'calling' object:>>> 's'.isupper()FalseHere is a string method that takes two parameters:>>>aStr= 'my cat is catatonic'>>>aStr.replace('cat', 'dog')'mydog isdogatonic'
Introduction to Computing Using Python
Strings are immutable
A string isimmutable -- once createditcan not bemodifiedWhen a string method returns a string, it is a different object; the original string is not changed>>>aStr= 'my cat is catatonic'>>>newStr=aStr.replace('cat', 'dog')>>>newStr'my dog isdogatonic'>>>aStr'my cat is catatonic'However, you can associate the old string name with the new object>>>aStr= 'my cat is catatonic'>>>aStr=aStr.replace('cat', 'dog')>>>aStr'mydog isdogatonic'
Introduction to Computing Using Python
Python string methods
Python hasmany very useful stringmethodsYoushould always look for and use an existing string method before coding it again foryourself.Here are somes.capitalize()s.count()s.endswith() /s.startswith()s.find() /s.index()s.format()s.isalpha()/s.isdigit()/s.islower()/s.isspace()s.join()s.lower() /s.upper()s.replace()s.split()s.strip()
Introduction to Computing Using Python
Python string method documentation
You can find the meaning of each of these string methods in the Python documentationSome operations on strings also workwith other sequence types, both mutable andimmutable.For example:x in sx not in ss+ ts*n / n*slen(s)min(s)max(s)
Introduction to Computing Using Python
Strings and the print() function
The print() function always prints a string. The input() function always inputs a string.Every object in Python has a string representation. Therefore, every object can be printed.When you print a number, a list or a function it is the string representation of the object that is printedprint() takes 0 or more arguments and printstheir stringrepresentations, separated by spaces>>> print('pi =', 3.14)pi = 3.14>>>deff():pass>>> print(f)<function f at 0x02C4BD20>
Introduction to Computing Using Python
The print separator and end
By default, print() separates multiple outputs with spacesYou can change this to any string that you want, for example, a colon and a space (': ')>>> print(1, 2, 3,sep=':')1: 2: 3By default, print()endsitsoutputwitha newline ('\n')>>> foriin range(3):print(i)012You can changethis, for example, to a hyphen>>>foriin range(3):print(i, end='-')0-1-2-
Introduction to Computing Using Python
The string format method
The string format() method allows you detailed control over what is printed and its arrangement (including alignment; width; your choice of date, time and number formats; and many other things).Here is an example of hows.format() can be used to control what is printed:>>> print('{} is{}'.format('Big Bird', 'yellow'))Big Bird is yellow>>> print('{} is {}'.format('Oscar', 'grumpy'))Oscar is grumpy
0
Embed
Upload