Python notes

Collection of random notes and snippets I’ve needed to look up too often.

These are not in any particular order or arranged anyhow.

Most of these are joinked from Stackoverflow.


Variable as function name

globals()['use_variable_as_function_name']()

is equivalent to:

use_variable_as_function_name()

Read file into variable

with open(filename, 'r') as file:
    var = file.read()
file.close()

for loop number range

for i in range(0,10):
    print("i is", i)

Adding characters to string

Strings are immutable so you can’t insert characters into an existing string. You have to create a new string.

text = "Value"
text_new = "d" + text
print(text)

Output:

dValue


Capitalize a string

text = "cat"
print(text.capitalize())

Output:

Cat


Dictionaries

Python dict:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Iterate over keys of a dict:

for item in thisdict.keys():
    print(item)

Output:

brand
model
year

Same for values:

for item in thisdict.values():
    print(item)

Output:

Ford
Mustang
1964


Iterate and enumerate list

stuff = ["Milk", "Eggs", "Corn", "Dirt", "Stone", "Banana", "Car"]

for idx, item in enumerate(stuff):
    print(idx, item)

Output:

0 Milk
1 Eggs
2 Corn
3 Dirt
4 Stone
5 Banana
6 Car


Check if variable is in list

sample = ['one', 'two', 'three', 'four']
var = "four"

if var in sample:
   print("four is in list")

Check if any of wanted characters is in string

s = "Hello Kebab"
chars = set('0123456789$,')

if any((c in chars) for c in s):
    print('Found')
else:
    print('Not Found')

Split string from character

s = "www.example.com"

parsed = s.split('.')
print(parsed)

Produces a list

['www', 'example', 'com']

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment