Concatenation
print("hello, " + name)
F-string
print(f"hello, {name}")
Adds space automatically sep=" "
print("hello, ", name)
Replace automatic new line end="\n"
print("hello, ", end="")
print(name)
Print ""
inside of " "
print('hello, "friend"') or print("hello, \"friend\"")
Remove char
from string
name = name.remove("c")
print(f"hello, {name}")
Remove whitespace before and after word
name = name.strip()
print(f"hello, {name}")
Remove prefix
str.removeprefix("$")
Remove suffix
str.removesuffix("%")
Replace one argument by another
s = "hello world"
s = s.replace(" ", "...")
Output:
`hello…world`
Capitalize first letter of first word
name = name.capitalize()
print(f"hello, {name}")
Capitalize first letter of each word
name = name.title()
print(f"hello, {name}")
Combine several methods
name = name.strip().title()
or
name = input("What's your name? ").strip().title()
Split sentences
first, last = name.split(" ")
print(f"hello, {first}")
Python interactive mode >>>
`python` to enter
`ctrl + d` to exit
Convert user input to int
or float
x = int(input("What's x? "))
x = float(input("What's x? "))
Round float to the nearest integer
x = float(input("What's x? "))
y= float(input("What's y "))
z = round(x + y)
Specify the number of digits to round to
round(number[n, ndigits])
z = round(x / y, 2)
or
print(f"{z:.2f}")
Format long numbers to include commas or points
print(f"{z:,}")
Define our own function
def function_name():
...
...
def hello(to):
print("hello,", to)
Assign a default value to the parameter to
def hello(to="world")
print("hello,", to)
hello()
name = input("What’s your name? ")
hello(name)
Define a main()
function
def main():
name = input("What's your name? ")
hello(name)
def hello(to="world"):
print("hello,", to)
main()
Very important to call
main()
at the end of the file and to pass the variable between functions (scope)
Define a function that returns square of n
def square(n):
return n * n
or
return pow(n, 2) #(number, exponent)
Define a function to raise to the power of 2
def power(n):
return n ** 2
Split a camel case string (camelCaseString) into several substrings (regex
)
import re
def split_camel_case(s):
return re.split("(?=[A-Z])", s)
Concatenate all elements of a list into a single string
"<Separator>".join(list)
Iterate through a string to find vowels
def vowelless():
vowels = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"]
for c in txt:
if c in vowels:
…
Irritate through each index [i]
and character c
in a string
for i, c in enumerate(string):
…