The Noobs of Python: Ep.3.0 - Methods to the Madness

Moving on to Ep.3 Method to the Madness we touch on... wait for it... Methods !
Methods are accessed using a command that follows the variable name immediately after a period (dot) and terminates in parentheses, which may or may not contain further arguments. In welcome.join(seq), join() is the method. Methods are like functions that are specific to an object, such as a data type in this instance. The string type has the method join() which takes a sequence as an argument and returns a single string made up of the elements of the sequence joined together with copies of the original string between them.

Q: Wow that sounds like a lot to do, what are the most popular methods() ?
A: So lets start with The upper(), lower() String Methods. The upper() and lower() string methods return a new string where all the letters in the original string have been converted to uppercase or lower-case, respectively. Nonletter characters in the string remain unchanged. So lets open up idle3 and give this code snip a try:

>>> welcome = 'hello world'
>>> welcome = welcome.lower()
>>> welcome
'hello world'
>>> welcome = welcome.upper()
>>> welcome
'HELLO WORLD'
>>>

Note that these methods do not change the string itself but return new string values.
If you want to change the original string, you have to call upper() or lower() on the string and then assign the new string to the variable where the original was stored.
This is why you must use welcome = welcome.upper() to change the string in welcome instead of simply welcome.upper().

print('Welcome to The Noobs of Python !\n Are you interested in learning python today?')
print('Yes | No | Maybe ?')

feeling = input()
if feeling.lower() == 'yes':
	print('Great !')
elif feeling.lower() == 'no':
	print('Well maybe next time !')
else:
	print('You should consider participating, by either commenting or posting you code!')

The upper() and lower() methods are helpful if you need to make a
case-insensitive comparison. The strings 'YES' and 'YEs' are not equal to
each other. But in the previous small program, it does not matter whether
the user types YES , YeS , or yES , because the string is first converted to
lowercase. Adding code to your program to handle variations or mistakes in user
input, such as inconsistent capitalization, will make your programs easier
to use and less likely to fail.

Another set of methods that could be helpful would be the .isupper() and .islower()

Community Challenge: The isupper() and islower() methods will return a Boolean True value if the string has at least one letter and all the letters are uppercase or lowercase, respectively. Otherwise, the method returns False. So post your examples/questions about .isupper() and .islower() in the comment section

Q: Wow, that was cool, are there any more methods I would use regularly with Lists?
A:Lets talk about : The join() and split() String Methods. The join() method is useful when you have a list of strings that need to be joined together into a single string value. The join() method is called on a string, gets passed a list of strings, and returns a string. The returned string is the concatenation of each string in the passed-in list. Fire up idle3 again and lets try another code snippet! :

>>> sith =['Vader', 'Palpatine', 'Maul', 'Dooku']
>>> ' '.join(sith)
'Vader Palpatine Maul Dooku'

Q: So what does.split() do?
A: The .split() method does the opposite of .join() It’s called on a string
value and returns a list of strings, so lets get back to idle3 :

`>>> 'Welcome to The Noobs of Python Ep.1'.split()
['Welcome', 'to', 'The', 'Noobs', 'of', 'Python', 'Ep.1']
>>>`

By default, the string 'Welcome to The Noobs of Python Ep.1' is split wherever whitespace characters such as the space, tab, or newline characters are found. These white­
space characters are not included in the strings in the returned list. You can
pass a delimiter string to the split() method to specify a different string to
split upon.

`>>> 'Welcome to The Noobs of Python Ep.1'.split('o')
['Welc', 'me t', ' The N', '', 'bs ', 'f Pyth', 'n Ep.1']
>>>`

A common use of split() is to split a multiline string along the newline
characters so let's go back to idle3 once again:

`>>> example = '''What will we cover?
Simple code and some Regex to test the boundary of what we know.
I learn more when challenged and hopefully some of you do as well.
Post your questions or code snippets and lets learn together as a community !

Thanks to all involved
Miguel'''
>>> example.split('\n')
['What will we cover?', 'Simple code and some Regex to test the boundary of what we know.', 'I learn more when challenged and hopefully some of you do as well.', 'Post your questions or code snippets and lets learn together as a community !', '', 'Thanks to all involved', 'Miguel']
>>> `

Q: Wow. All this is great, It's time for me to get some practice in tolet it sink in...
A: Then hit the comment section with some code and ask if you need help! Enjoy

Thanks to all the community member contributing and asking for more. We will be going in depth into some of the Ep.x as we get more question from the comment sections. Leading up to the Intermediate 'The Knights Of Python'

Keep on coding Code_Warriors

Coming soon : The Noobs of Python : Ep.4 - What's your Function / Define Functions

4 Likes

Type-Specific Methods

.replace() , .find() and .format()

>>> intro = '''If this is your first time at Level1Techs, welcome to our community forums!
If you are here just to read the rules, please proceed below.'''
>>> intro.find('e')
25
>>> intro.replace('e', 'E')
'If this is your first timE at LEvEl1TEchs, wElcomE to our community forums!\nIf you arE hErE just to rEad thE rulEs, plEasE procEEd bElow.'
>>> 'Modern {0} have fancy {1} setups'.format('cars', 'infotainment')
'Modern cars have fancy infotainment setups'
>>>

Getting Help
The methods introduced in the prior section are a representative, but small, sample of
what is available for string objects. In general,we can't look at all object methods.
For more details, you can always call the built-in dir function. This function lists variables assigned in the caller’s scope when called with no argument; more usefully, it returns a list of all the attributes available for any object passed to it. Because methods are function attributes, they will show up in this list. Assuming intro is still the string, here are its attributes on Python 3.x

>>> dir(intro)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', 
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', 
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 
'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 
'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

Ofcourse if you have any questions just ask/post...

1 Like

Here's another handy method for dictionaries, .get()
I used it in episode 4 and thought I'd come back to cover it.

.get() is a method that can be used on dictionaries to fetch the definition of a given key. It takes one argument - the key.

It can also, optionally, take another argument, which is the value to return if the given key isn't found in the dictionary the method's being used on - the default for this is None. Be warned! Some guides will state this argument as being a keyword argument (you have to do "default = " instead of just placing the value you want to be the default between the parenthesis. This is no longer the case!

See the quoted post for a usage example.

Edit: If you want to see how to write functions with optional arguments like the .get() method's optional default value, see this post in episode 4! Yep, go back again! lol:

2 Likes

Other than dir() there is also help() function.

For instance we called dir() function on welcome string:

>>> welcome = 'welcome to noobs of python at level1 forums'
>>> welcome
'welcome to noobs of python at level1 forums'
>>>
>>>


>>> dir(welcome)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

We have method ` title()` for example. To get information on what that method does we can simply call `help()` function. As each method might behave diferently with different data type you need to specify for whitch data type you are calling the help man page. You can do:

>>> help(str.title)

or

>>> help(welcome.title)

Both will return:

Help on built-in function title:

title(...) method of builtins.str instance
    S.title() -> str

Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.

And now we know to change all first letters to capitals in out `welcome` string we can simply use ` title()` method.

>>> print(welcome)
welcome to noobs of python at level1 forums
>>> print(welcome.title())
Welcome To Noobs Of Python At Level1 Forums
>>>

The above is just something i figured out by myself but using help() function is like reading man pages in linux/unix most of the time is very complicated and doesn't give you examples. @Miguel_Sensacion now since we dived into the methods maybe we can do another noobs of python segment about how to get more help from pythons build-in documentation and how to read it?

1 Like