Python 3home |
Introduction to Python
davidbpython.com
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.
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.
This "transforming" method returns a new string with a string's value uppercased.
upper() string method
var = 'hello'
newvar = var.upper()
print(newvar) # 'HELLO'
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'
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.
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.
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")
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.")
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)
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
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.
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.
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