Python String and Math Functions Cheatsheet
String Related Functions
- len(str) — returns the length of ‘str’
- str.format(c) — formats. Use {:.2f} to round to 2 decimals. Always 2, even if the last digit is 0. Uses c as quantity. {:d} for integer types.
- str.upper(), str.lower() — makes uppercase, makes lowercase
- str.capitalize() — makes the first letter of a sentence uppercase
- str.replace(“a”, “b”) — substitutes each case of “a” with “b”
- str[0] — returns the first character of the string
- str.title() — makes all first letters of words uppercase
- str.count(“a”) — returns the count of “a” in str
- str.find(‘object’, n) — will return the lowest position of ‘object’ in a string starting at n position (if object is not found, it will return -1)
- input(“Text”) — Reads user input as a string argument (Use int(input(“Text”)) or float(input(“Text”)) if you want to input a number)
- int(x), str(x), float(x) — converts x to an int, str, or float, respectively.
- Alphabetical order: numbers < uppercase < lowercase
Math Functions and Calculation Usage
- math.ceil(x), math.floor(x) — rounds up or down to the nearest value, respectively
- math.trunc(x) — deletes the decimals (math.trunc(123.923495) = 123)
- math.pi = 3.14159…
- math.pow(x, y) — returns x raised to the power y (as a float)
- pow(x, y) does the same thing but returns as an integer
- math.sqrt(x) — gives the square root of a number x, returns float
- abs(x) — gives the absolute value of x
- min(a, b), max(a, b) — returns the min/max of the two parameters (you can use more than two parameters)
- x % y — remainder of x / y (2 % 4 = 2, 4 % 3 = 1, -4 % 3 = 2)
- If the numerator is less than the denominator, it returns the value of the numerator — however, not the case with negative numbers)
- x // y — integer division with no remainder (5 // 4 = 1, -5 // 4 = -2), has the same effect as math.floor()
- x / y — float division (or simply regular division)
- c = a>b, if a is greater than b, sets c to True, otherwise sets c to False
- round(float, n) — rounds float to n decimals, drops trailing 0’s.
Escape Characters
- \n – end the current line
- \t – skip one tab space
- \’ do not interpret (‘) as a delimiter – essentially print the ‘
- \” do not interpret (“) as a delimiter – essentially print the “
- \\ do not interpret (\) as a delimiter – essentially print the \
If Statement
if (condition):
Block 1
elif (condition):
Block 2
else:
Block 3
Function Definition and Function Rules
- def function(parameter(s)):
function processes
return (whatever variable you’re manipulating)
print function(argument(s)) - def funct(a):
print(a)
x=funct(6) # doesn’t set x equal to anything, but will print 6 - def funct2(b):
return(b)
x=funct2(6) # will set x equal to 6 because it’s returning the value - def funct3(c):
print(c)
print(funct3(6))
Output:
6
None
Don’t forget:
- int(input()) if inputting a number
- Import math – can also do import math as m to shorten your code a bit
- You can also say from math import x where x is the function you need, that way you don’t have to write math.x(), you can just write x()
- count spaces when counting in len()
- \n and \t count for 1 char each
- :(colon) after def function(x) and if (condition), indent appropriately
- You can’t add integers to strings, but you can multiply integers and strings. For example, if you code “x = 100” and “y=’10 times 10 equals ‘”, there will be an error if you try to do “print(y + x)”. To print such, you must either cast x as a string or use a comma instead of a plus sign. (“print(y + str(x))” or “print(y,x,sep=”)”) However, if you do “print(y * x)”, the program will print “10 times 10 equals ” 100 times.
- Ex: s = ”’sdfsf \t ” ”’ -> not a syntax error three quote variable is okay
- Can use str(float or int variable) to concatenate rather than using a separator in a print function or string variable
- print(“What’s up dawg”, variable, sep=” “, end=”\n”) sep defaults to one space end defaults to “\n”) be equal to what was in the return.
- BE CAREFUL using // and % with negative values! You get different outputs (-7//3 means math.floor(-7//3) so the result is -3)
- global variables can be used in all functions, whereas local variables are function-specific
How to separate numbers:
- 123//100=1
- 123//10%10=2
- 123%10=3
Terms
- Parameter–expected input of function
- Argument–actual input of a function
- Local variable–any variable inside a function
- Syntax error–error which causes the program to not run
- Semantic error–error which allows the program to run, but against the intention of the programmer