Python 3home |
Introduction to Python
davidbpython.com
Objects are capable of behaviors, which are expressed as methods.
var = 'Hello, World!'
var2 = var.replace('World', 'Mars') # replace substring, return a str
print(var2) # Hello, Mars!
Compare method syntax to function syntax.
mystr = 'HELLO'
x = len(mystr) # function len() (stands alone)
y = mystr.count('L') # method .count() (attached to the string variable)
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.
var = 'hello'
newvar = var.upper() # str, 'HELLO'
print(newvar) # 'HELLO'
This method does not take an explicit argument, because it works with the string object itself.
This "transforming" method returns a new string with a string's value lowercased.
var = 'Hello There'
newvar = var.lower() # str, 'hello there'
print(newvar) # 'hello there'
This method does not take an explicit argument, because it works with the string object itself.
This "transforming" method returns a new string based on an old string, with specified text replaced.
var = 'My name is Marie'
newvar = var.replace('Marie', '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
ex. 3.27 - 3.28
An f'' string allows us to embed any value (such as numbers) into a new, completed string.
aa = 'Jose'
var = 34
bb = f'{aa} is {var} years old.'
print(bb) # Jose is 34 years old.
Ex. 3.29
There are numerous options for justifying, formatting numbers, and more.
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 decimal places) :.2f # as float (2 decimal places) :, # 000's comma separators :,.2f # 000's comma separators with float rounded to 2 places
There are even more options, you can search online for details.
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. ex 3.29
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
Professional coders respect good style because it makes code easier to read.