"hello world".find("world", 6)6
Introduction to Software Engineering (CSSE 1001)
In Assignment 1 and during file processing we are/will be working extensively with strings,
We are able to replicate the functionality of any string method with our current tools.
Strive to implement any string method you use at least once.
There are a myriad of built-in string methods in Python. You can review them by searching the web or doing
help(str)
...
| capitalize(self, /)
| Return a capitalized version of the string.
|
| casefold(self, /)
| Return a version of the string suitable for
| caseless comparisons.Type Enter to scroll and q to escape or quit help.
We will eventually learn that strings are objects.
Objects have methods which are like functions but have different invocation syntax.
For instance we do not say
capitalize("hello")
NameError: name 'capitalize' is not definedbut rather
"hello".capitalize() # Note the ()
'Hello'For information on a particular method do
help(str.find)
find(...)
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as with slice notation.
Return -1 on failure.
(END)The square brackets in the parameters for find:
find(sub[, start[, end]])
indicate the parameter is optional.
This rule recurses, that is to say, optional parameters can have optional parameters.
The comprehensive ways of calling find are:
"team".find("I"), "team".find("I",1), "team".find("I",1,-1)whereas find(1,-1) is not allowed since sub is required.
"hello world".find("world", 6)6
"hello hello".find("hello") 0
"hello hello".find("hello", 1) 6
"hello hello".find("hello", 1, 3) -1
The following may be accomplished by invoking the appropriate string-method correctly.
Exercise 1 Convert a string of text into title format.
For example,
`a tale of two cities'
should be converted to
`A Tale Of Two Cities'.
Exercise 2 Write a function that, given a word and integer width, centers the word in a sequence of xs.
foo('spam', 10)'xxxspamxxx'
foo('101', 20)'xxxxxxxx101xxxxxxxxx'
Default split at space.
"a b c".split()['a', 'b', 'c']
"axbxc".split()['axbxc']
"axbxc".split('x')['a', 'b', 'c']
"axbxc".split('bx')['ax', 'c']
Useful for csv files.
"a, b, c".split(',')['a', ' b', ' c']
Removing tailing/leading spaces.
"a, b, c".split(', ') ['a', 'b', 'c']
",".join(["A", "B", "C"]) 'A,B,C'
"".join(["A", "B", "C"]) 'ABC'
", ".join(["A", "B", "C"]) 'A, B, C'
"".join(["A", "B", "C"])
'ABC''ABC'
Sometimes datatypes come with extra functionality by way of methods. In particular, there are many string methods that will aid with text processing.