python cheat sheet

25

Best Python Cheat Sheet PDF:
https://websitesetup.org/wp-content/uploads/2020/04/Python-Cheat-Sheet.pdf
a = 1  # initialization
def foo():
    """
    This is a function docstring
    You can also use:
    ''' Function Docstring '''
    """
>>> spam = 'Hello'
>>> spam
'Hello'
txt = "this is a wild string"

print(txt.replace("i", "x"))  # print string with all i characters replaced with x
print(txt.replace("i", "x", 2))  # print string with first two i characters found with x
print(txt.upper())  # print string in all uppercase letters
print(txt.lower())  # print string in all uppercase letters

print(ord('A'))  # print the ordinal value of a character
print(chr(95))  # print character from its ordinal value
print('Yes' * 5) # print string Yes 5 times

# Reference strings by index
print(txt[0])  # print first letter of string from starting index
print(txt[0:2])  # print first two letters from starting index
print(txt[1:])  # print all characters except the first letter
print(txt[0::2])  # print every second character
print(txt[::-1])  # print string in reverse
print(txt[-1])  # print the last character in a string
print(txt[-2:])  # print the last who characters in a string

# check if a wild is found in txt
if "wild" in txt:
  print("wild is found in txt")

# check if a blah is not found in txt
if "blah" not in txt:
  print("is not found in txt")

# Check if txt starts with this
if txt.startswith("this"):
  print("Starts with this")

# check if txt ends with ing
if txt.endswith("ing"):
  print("Ends with ing")

# Split a string into a tuple when the delimiter is first encountered
txt = 'random-data'

data_split = txt.partition('-')
print(data_split)
# output ('random', '-', 'data')

len(txt)  # Return length of string

# loop through each character in string
for char in txt:
  print(char)

# Display price with commas and 2 digit precision
price = 9749000
display_price = f"My price {price:,.2f}"
print(display_price)
>>> print('Hello world!')
Hello world!

Comments

Submit
0 Comments