Python 3

home

Introduction to Python

davidbpython.com




Object Methods

object methods

Objects are capable of behaviors, which are expressed as methods.


Use object methods to process object values

var = 'Hello, World!'
var2 = var.replace('World', 'Mars')      # replace substring, return a str
print(var2)                              # Hello, Mars!

Methods are type-specific functions that are used only with a particular type.





methods vs. functions

Compare method syntax to function syntax.


mystr = 'HELLO'

x = len(mystr)          # int, 5

y = mystr.count('L')    # int, 2

print(y)                # 2

Methods and functions are both called (using the parentheses after the name of the function or method). Both also may take an argument and/or may return a return value.





string method: .upper()

This "transforming" method returns a new string with a string's value uppercased.


upper() string method


var = 'hello'
newvar = var.upper()

print(newvar)                   # 'HELLO'




string method: .lower()

This "transforming" method returns a new string with a string's value uppercased.


lower() string method


var = 'Hello There'
newvar = var.lower()

print(newvar)                   # 'hello there'




string method: .replace()

this "transforming" method returns a new string based on an old string, with specified text replaced.


var = 'My name is Joe'

newvar = var.replace('Joe', 'Greta')    # str, 'My name is Greta'

print(newvar)                            # My name is Greta

This method takes two arguments, the search string and replace string.





string method: .isdigit()

This "inspector" method returns True if a string is all digits.


mystring = '12345'
if mystring.isdigit():
    print("that string is all numeric characters")

if not mystring.isdigit():
    print("that string is not all numeric characters")

Since it returns True or False, inspector methods like isdigit() are used in an if or while expression. To test the reverse (i.e. "not all digits"), use if not before the method call.





string method: .endswith()

This "inspector" method returns True if a string starts with or ends with a substring.


bb = 'This is a sentence.'
if bb.endswith('.'):
    print("that line had a period at the end")




string method: .startswith()

This "inspector"method returns True if the string starts with a substring.


cc = input('yes? ')
if cc.startswith('y') or cc.startswith('Y'):
    print('thanks!')
else:
    print("ok, I guess not.")




string method: .count()

This "inspector" method returns a count of occurrences of a substring within a string.


aa = 'count the substring within this string'
bb = aa.count('in')
print(bb)             # 3 (the number of times 'in' appears in the string)




string method: .find()

This "inspector" method returns the character position of a substring within a string.


xx = 'find the name in this string'
yy = xx.find('name')
print(yy)             # 9 -- the 10th character in mystring




f'' strings for string formatting

An f'' string allows us to embed any value such as numbers into a new, completed string.


aa = 'Jose'
var = 34

# 2 arguments to replace 2 {} tokens
bb = f'{aa} is {var} years old.'

print(bb)                                  # Jose is 34 years old.





f'' string format codes

An f'' string allows us to embed any value such as numbers into a new, completed string.


overview of formatting

# text padding and justification
# :<15     # left justify width
# :>10     # right justify width
# :^8      # center justify width

# numeric formatting
:f         # as float (6 places)
:.2f       # as float (2 places)
:,         # 000's commas
:,.2f      # 000's commas with float to 2 places

examples

x = 34563.999999

f'hi:  {x:<30}'      # 'hi:  34563.999999                  '

f'hi:  {x:>30}'      # 'hi:                    34563.999999'

f'hi:  {x:^30}'      # 'hi:           34563.999999         '

f'hi:  {x:f}'        # 'hi:  34563.999999'

f'hi:  {x:.2f}'      # 'hi:  34564.00'

f'hi:  {x:,}'        # 'hi:  34,563.999999'

f'hi:  {x:,.2f}'     # 'hi:  34,564.00'

Please note that f'' strings are available only as of Python 3.6.





sidebar: method and function return values in an expression; combining expressions

The return value of an expression can be used in another expression.


letters = "aabbcdefgafbdchabacc"

vara = letters.count("a")         # 5

varb = len(letters)               # 20

varc = vara / varb                # 5 / 20, or 0.25

vard = varc * 100                 # 25


print(len(letters) / letters.count("a") * 100)  # statements combined





[pr]